Impl FnOnce for own Box implementation

I implemented my own Box because I want to store the vtable with the Box but ultimately I cannot call the FnOnce function that I tried to wrap in that Box, because I get this error: cannot move a value of type dyn FnOnce() -> bool: the size of dyn FnOnce() -> false cannot be statically determined. I figured that I have to implement the trait FnOnce for my own Box, but there are no good examples and just trying to look at the library source did not help. Can someone please explain how this all should fit together?

This is not possible on stable rust for two reasons. The first is that the Fn* family of traits is unstable and as such can't be implemented on stable rust. The second is that Box is special. The compiler knows that it is possible to move out of it. There is no way to replicate this on nightly. Rustc uses a so called lang item to find Box at alloc::boxed::Box. Lang items can only be defined once in the whole crate graph. In addition rustc only knows how to move out of Box because the exact layout of it is baked into the compiler. Attempting to change it will likely cause an ICE. Lastly Box has a special Drop implementation. In the source code of liballoc it is empty, but the compiler knows that it first has to call the drop glue for the inner type if it isn't moved out of followed by a call to the box_free lang item to deallocate the backing storage.

1 Like