DST Structs construction

⚓ Rust    📅 2025-10-21    👤 surdeus    👁️ 4      

surdeus

Info

This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: DST Structs construction

Hi! 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:

  1. Is there a better, more safe, way to do this?
  2. If not, can you show me how to correctly construct this with std::alloc::alloc?
  3. Do I need to mark this struct as #[repr(C)] or it can be constructed with #[repr(Rust)]?

4 posts - 3 participants

Read full topic

🏷️ Rust_feed