Construct structure with array member during runtime?

I'm having trouble understanding what you mean. But I think you want to know how to fix the compiler error, so that you can create a Layout from the Header type, the Payload type, and an array size N. To do that, instead of passing n as a runtime parameter, pass N as a const generic parameter.

You cannot use a runtime value n to do this, because the Sample struct type must be known at compile time.

use core::alloc::Layout;

pub(crate) fn sample_layout1<Header, Payload, const N: usize>() -> Layout
where
    Header: Sized,
    Payload: Sized,
{
    #[repr(C)]
    struct Sample<Header, Payload, const N: usize> {
        _header: Header,
        _payload: [Payload; N],
    }

    Layout::new::<Sample<Header, Payload, N>>()
}

fn main() {
    let layout = sample_layout1::<u64, u8, 8>();
    println!("{layout:?}");
}
2 Likes