Construct structure with array member during runtime?

Hi guys, I want to know the layout of a Sample structure by calling Layout::new instead of calculating it by myself. So I try to define this part of code to do so:

    pub(crate) fn sample_layout1<Header, Payload>(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>>()
    }

But I got complain from compiler that attempt to use a non-constant value in a constant. I understood that rustc requires all array sizes must be known during compiling, because the other code might use the structure definition.

However, the struct here is defined for layout calculating only and won't escape from the function scope. I wonder whether I have a way to bypass the limitation from rustc, or do I have a better way to do so?

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

If n is a runtime variable you can use Layout for "assisted" calculation

Layout::new::<Header>().extend(Layout::array::<Payload>(n)?)?.0.pad_to_align()
3 Likes

Hi @jumpnbrownweasel , thanks for your answer, but that's not my direction because the N cannot be changed to a const. It's known until the runtime. But thanks for your helping, I believe @Bruecki answer is what I want.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.