Unboxing boxes of unknown size

I have spent a lot of time trying to understand Rust, but there are one (probably pretty basic) topic i cant wrap my head around. How can i unwrap boxes when the compiler doesn't know how big the inner value will be at compile time. I am passing a lot of Box around between functions, but since i cant dereference it, how would i be able to extract the Path object out of the Box? Is it even possible? Any help would be appreciated!

Thanks :slight_smile:

For std unsized types like Box<Path> there's generally a conversion supplied.

The situation is trickier with type erasure (dyn Trait) but if you have a specific example, feel free to share it.

2 Likes

It's simply impossible. You can't unwrap a dynamically-sized value by-value. You can only manipulate DSTs via indirection.

If you have a Box<Path> and you want a &Path, then dereference and take the address immediately.

You totally can, as clearly demonstrated above. The problem lies not in the dereferencing itself, but in trying to use the resulting DST as a value (i.e., moving it). If you only use it as a place, everything works.


What @quinedot's solution above does is convert the DST to its statically-Sized counterpart. If that's what you want, then:

  • in the case of statically-typed DSTs (e.g., strings, paths, and slices), you'll have to rely on the type to provide a non-allocating Box<DST> -> DST::Owned conversion.

    These almost exclusively require unsafe under the hood. Do NOT try that at home; if you don't even understand how to get a reference from a box, then you are virtually guaranteed to mess up anything unsafe big time.

  • in the case of Box<dyn Any>, the only reasonable thing is to downcast it to a concrete type, which is already provided by the standard library.

  • if you have any other dyn Trait, then it's not directly possible to get to the underlying static type.

3 Likes