My questions is two parts (since I couldn't get the first part, I moved to the second part, which still left me with questions)
Part #1: How do you insert heterogeneous struct
types into a HashMap
? At first I thought to do it via an enum
E.g.,
enum SomeEnum {
TypeA,
TypeB,
TypeC,
}
struct TypeA{}
struct TypeB{}
struct TypeC{}
let hm = HashMap::new();
hm.insert("foo".to_string(), SomeEnum::TypeA);
hm.insert("bar".to_string(), SomeEnum::TypeB);
hm.insert("zoo".to_string(), SomeEnum::TypeC);
But I get a "Expected type: TypeA, found type TypeB"
error
Part #2: So then I went to the docs and read up on Using Trait Objects that Allow for Values of Different Types, and simplified the problem down to just trying to put heterogeneous types into a Vec
. So I followed the tutorial exactly, but I'm still getting the same type of error (in the case of the docs, the error is now "Expected type SelectBox, found type Button"
.
I know static typing is huge part of Rust, but can anyone tell me/show me/refer me to any info related to putting different struct
types in either a Vec
or HashMap
.
Rust won't do any mapping of types to enum variants for you - you need to explicitly include the data in the enum itself:
That said, if the only context in which you'll need to use those struct types is when you're using that enum, you can combine them like so: