Const generic bool optional field

I need a struct sometimes with a field and other times without, but enforced at compile time instead of using an Option. This is kinda possible with const generics:

struct Foo<const B: usize> {
    bar: [String; B]
}

fn main() {
    Foo::<1> {
        bar: ["hello".into()]
    };
    Foo::<0> {
        bar: []
    };
}

The obvious next step would be to have the type parameter be a Bool and then hide the ugliness behind a pretty type interface. Is this already possible? If not, is there a path to get there eventually, and are there workarounds that get me closer to my goal in the meantime?

You can use type generics instead.

2 Likes