DST Structs construction
⚓ Rust 📅 2025-10-21 👤 surdeus 👁️ 4Hi! I' currently trying to implement a struct where the last field is a DST (dynamic sized type) type, causing the struct to be a DST too. The code looks like
struct Foo {
bar: u32,
baz: [i8],
}
impl Foo {
fn new(bar: u32, baz: &[i8]) -> Arc<Self> {
todo!();
}
}
I want to be able to construct this struct with a function new, that given a bar: u33 and a baz: &[i8] returns an Arc. The only solution I've currently found is by manually allocating memory with std::alloc::alloc and doing some unsafe ptr calls, finally casting the pointer to a Box and then the Box to an Arc.
So my questions are:
- Is there a better, more safe, way to do this?
- If not, can you show me how to correctly construct this with std::alloc::alloc?
- Do I need to mark this struct as #[repr(C)] or it can be constructed with #[repr(Rust)]?
4 posts - 3 participants
🏷️ Rust_feed