How to put heterogeneous types into a Rust structure [duplicate]

穿精又带淫゛_ 提交于 2020-01-21 12:31:32

问题


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.


回答1:


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 {});
}


来源:https://stackoverflow.com/questions/51936299/how-to-put-heterogeneous-types-into-a-rust-structure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!