How to construct an unsized struct / How to construct a struct with an slice?

Yes, that solution would work. Although I'd prefer to cast ptr to a *mut () before putting it through slice_from_raw_parts_mut; that way, we'd never actually have any pointers that span into unallocated memory. Alternatively, I'd use an unsizing coercion to avoid having to manipulate the length at all, as in my new_from_array() function above, but this way is also sound. (Here's an example of how it would be adapted.)

1 Like

I don't even know about this way... I learned a lot from this post. :grinning:

1 Like

Thanks for answers. That's pleasure to read :slight_smile:

Very cool!
But what if x and elements of slice have different types?

        let mut v = Vec::with_capacity(len + 1);

That code does not work then. How to construct such a structure with a slice?

In the general case, this is quite tricky, since we must manually compute the size and alignment of the full struct. For repr(C), a struct ending with a [T] slice of length N will be laid out as if it ends with a [T; N] array. This means that padding bytes can occur both before and after the slice, so that the slice is correctly aligned and so that the size of the entire structure is a multiple of its alignment.

Is there any particular type you're trying to initialize, or are you asking about the general case?

1 Like

Just curiosity. Original solution is good enough. Thanks!

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.