How to put heterogeneous types into a Rust structu

2020-04-10 03:51发布

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
1条回答
戒情不戒烟
2楼-- · 2020-04-10 04:22

Rust won't do any mapping of types to enum variants for you - you need to explicitly include the data in the enum itself:

use std::collections::HashMap;

enum SomeEnum {
    A(TypeA),
    B(TypeB),
    C(TypeC),
}

struct TypeA {}
struct TypeB {}
struct TypeC {}

fn main() {
    let mut hm = HashMap::new();
    hm.insert("foo".to_string(), SomeEnum::A(TypeA {}));
    hm.insert("bar".to_string(), SomeEnum::B(TypeB {}));
    hm.insert("zoo".to_string(), SomeEnum::C(TypeC {}));
}

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:

use std::collections::HashMap;

enum SomeEnum {
    A {},
    B {},
    C {},
}

fn main() {
    let mut hm = HashMap::new();
    hm.insert("foo".to_string(), SomeEnum::A {});
    hm.insert("bar".to_string(), SomeEnum::B {});
    hm.insert("zoo".to_string(), SomeEnum::C {});
}
查看更多
登录 后发表回答