Is there any crate can hold multiple types but only one is possible

Hi, guys. Is there any crate out there which can hold multiple types but only one type is possible, much like an union.

Say,

struct Foo {
    a: SomeType<AType, BType, CType>,
}

so I can do like

let mut foo = Foo {
    a: SomeType::new(AType);
};
// foo.a is a AType.

foo.a = SomeType::new(BType);
// foo.a is a BType by now.

Can't you just use an enum?

5 Likes
enum SomeType<A, B, C> {
    AType(A), BType(B), CType(C),
}

SomeType::BType(btype_instance);

If you want to store the state, but not a value of the type, then a regular enum should suffice. Types in Rust aren't objects, so you can't store them directly. You could do something clever with extra traits and associated types implemented on unit structs to mark something as "a type", but the easiest way is to just use a regular enum and a match.

2 Likes

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.