desugaring-based placement-in (just in, no box); take-5 branch by pnkfelix · Pull Request #27215 · rust-lang/rust (original) (raw)

Oh, I've been wanting this for ages, but it was blocked on having a placement API at all.
That is correct, you evaluate v first, then n, then allocate n * sizeof(v) bytes and only afterwards you can copy v into n different slots.
You can also do it for trait objects from Sized types: you allocate the size of the type, write the typed value in, then save the vtable pointer in the fat pointer without any unsizing step.

Direct allocation of unsized types is necessary to construct types that do not allow type-param-based unsizing, such as:

struct str([u8]); struct Entity { id: u32, kind: Kind, name: &str, value: Any }

Wouldn't &str(*b"foo") be a nice desugaring of "foo"? Admittedly, it couldn't be exposed everywhere without allowing invalid UTF-8. Unsafe fields/constructors, anyone?