Home > Blockchain >  Vec of Vecs, where the inner Vec to only contain one type, but different types in the outer Vec
Vec of Vecs, where the inner Vec to only contain one type, but different types in the outer Vec

Time:08-19

I'm trying to hint at an inner Vec to only contain one type of enum discriminant. I can use a trait, or something if that can work here too.

Is this possible, or is there another way of doing this?

Asking because I just want no accidental wrong type, even though the code can be checked during run-time, I'd rather have it at compile time.

enum Kind {
    Apple(Apple),    
    Banana(f32),
}

/*
This could also be two different types:
struct Apple { v: f32 };
struct Banana { v: u8 }; 
*/

struct Outer {
    inners: Vec<Inner<Kind::?>>,  // I want to specify that the Inner should be a specific discriminant.
    // Maybe an option of a T? where: T: Apple | Banana?
}

struct Inner<T> {
   // I want all these to either be `Kind::Apple` or `Kind::Banana`, or the same type.
   items: Vec<T> 
}

The other option I can think of is just expanding into the struct, and not use an enum.

struct Outer {
    apples: Vec<Apple>,
    bananas: Vec<Banana>,
}

Edit: I forgot to mention there are values in the enum and the struct.

CodePudding user response:

No, this is not possible. Kind represents a domain of values, and Kind::Apple and Kind::Banana together are the entire domain.

Kind is a type. The variants of Kind are values of the Kind type; they aren't themselves types.

It's a bit like asking if you could have a Vec of i32 values, but specify at the type level that the i32s in one Vec must all be the same value, like a Vec<0_i32>, which doesn't make sense either. You might as well have a Vec<()>, since you can infer that the value is 0.

If the enum variants have a payload, you could store just the payload. For example:

enum Kind {
    Apple(Apple),
    Banana(Banana),
}

struct Apple { /* ... */ }
struct Banana { /* ... */ }

Now you could have a Vec<Apple> and a Vec<Banana>, but you'd just be storing values of those types, and the "kind" is inferred by which vector you get the payload from.

  • Related