如何将异构类型放入Rust结构中

sem*_*267 3 rust

我的问题分为两部分(因为我无法得到第一部分,我转到了第二部分,这仍然让我有问题)

第1部分:如何将异构struct类型插入到HashMap?起初我想通过一个enum

例如,

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);
Run Code Online (Sandbox Code Playgroud)

但是我收到了一个"Expected type: TypeA, found type TypeB"错误

第2部分:然后我去了文档并阅读了使用允许不同类型的值的特征对象,并将问题简化为仅尝试将异构类型放入Vec.所以我完全按照教程,但我仍然得到相同类型的错误(在文档的情况下,错误现​​在"Expected type SelectBox, found type Button".

我知道静态打字是Rust的重要组成部分,但任何人都可以告诉我/给我看/给我任何与将不同struct类型放入a Vec或者相关的信息HashMap.

Joe*_*lay 5

Rust不会为您执行任何类型到枚举变体的映射 - 您需要在枚举本身中明确包含数据:

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 {}));
}
Run Code Online (Sandbox Code Playgroud)

也就是说,如果您需要使用这些结构类型的唯一上下文是在使用该枚举时,您可以将它们组合起来:

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 {});
}
Run Code Online (Sandbox Code Playgroud)