|
|
Log in / Subscribe / Register

Rust functions are a bit more complicated than described

Rust functions are a bit more complicated than described

Posted Nov 25, 2025 9:55 UTC (Tue) by ras (subscriber, #33059)
In reply to: Rust functions are a bit more complicated than described by NYKevin
Parent article: DebugFS on Rust

> But in a mad anomaly, there is a blanket Box<T: FnOnce + ?Sized> implementation

I hadn't noticed FnOnce talking self rather than &mut self. But Box<T: FnOnce + ?Sized> has the same sort of twisted logic Box<[u8]> uses. In both cases, there will never be an actual instance of the unsized type. The instance had to be sized, because Box has to pass its size to the memory allocator. You can't call Box::<[u8]>::new() for that reason.

A variable of type Box<[u8]> will always hold an instance whose type was Box<[u8; N]>, which is a sized type. The [u8; N] value was put into the memory allocated by the Box by the compiler intrinsic box_new(), and it knows to store N along with the array. Later the &**self somehow constructs an slice from the information stored by box_new(). There is some magic going in in the &**, because how did it know the value it is dereferencing was created by box_new()? But apart from that it seems pedestrian.

Similarly, the variable may have type Box<T: FnOnce + ?Sized>, but the thing stored in the box isn't ?Sized - it has a very definite size, and just like the &**self, FnOnce::call_once() could know what it was, if it cared. I don't think the rules about self being sized are being bent too much, at least not more than &**self bends them.

The quirk I did notice is a Box is defined as tuple of length 2, viz: Box<...>(Unique<T>, Allocator). So presumably &**self in deref() is being interpreted as &**self.0. I don't know why &**self is acceptable. Allocation will be a zero sized type, but if I use a ZST in that way I'm still not allowed to write to dereference the tuple with * in my code.

It's all very magic.


to post comments


Copyright © 2026, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds