My mental model of data layout in Rust was that all structs' sizes have to be known at compile-time, which means all of their properties have to be known at compile-time recursively. This is why you can't have a struct member that's simply a trait (and why enums have to be used in place of union types): the size can't be known, so instead you have to use either
- A generic, so the trait gets "reified" to a size-known struct at usage time
- An enum, which has a finite set of possible size-known layouts
- A
Box, whose size is known because it's just a pointer
But in the docs for Path, it says:
This is an unsized type, meaning that it must always be used behind a pointer like
&orBox. For an owned version of this type, seePathBuf.
Yet Path is neither a trait nor a generic struct, it's just a plain struct.
What's wrong with my mental model that this can be possible?
I found this explanation of what dynamically-sized types are, but I still don't understand, how I would make one of my own. Is doing so a special privilege reserved for the language itself?
Pathcontains aOsStrwhich is a slice of memory (without a defined length). So as the content is unsized, thePathstruct is unsized as well.dyn Trait) are always DSTs, the opposite isn't true. Building your own unsized struct and making it useful is a complicated subject with many requirements and few benefits.struc Foo {bar:str}or (bar:[u8]) which is unsized. I would expect that rust optimizes it to contain just the contents ofbar. And since it is unsized, you cannot assign it to a local (stack) variable. On the heap variable sizes are manageable (as with strings and slices).