Given a Box holding a dyn Trait object, is there any way to construct a Boxed unsized type?
For example, suppose I have a (potentially) unsized type:
pub struct IdAndData<T: ?Sized> {
id: i32,
data: T,
}
Is there any function that implements this signature?
pub fn construct_from_box<T: ?Sized>(id: i32, data: Box<T>) -> Box<IdAndData<T>> {
todo!()
}
This would allow something like:
fn main() {
let anything: Box<dyn Any> = Box::new(123);
let tagged_anything = construct_from_box(1, anything);
}
I know it would have to consume data, allocate enough space for the id and data together, then move data to the new allocation. This seems possible (we know all of the sizes at run-time), but the Rustonomicon suggests that it can only be done with an unsizing coercion with slices.
Is there any safe way to do this operation?