Is possible to have different members in struct based on const generic type?

I want to make a struct, that acts as either [T; N] or Vec<T>,
according to the const generic type.

That is, I want to share the code for a container, for both heapless and heapful version.

This is simple to do in C++ using template, but how to do this in Rust?

For example

pub struct MaybeOnHeap<T, const N: usize, const HEAPLESS: bool> {

}

/// When HEAPLESS == true, same layout as `[T; N]`
pub struct MaybeOnHeap<T, const N: usize>([T; N]);
/// When HEAPLESS == false, same layout as `Vec<T>`
pub struct MaybeOnHeap<T, const N: usize>(Vec<T>);

Here's a way, though I'm not sure how far you could ergonomically push it.

1 Like