使用任何类型的元组定义向量

时间:2016-08-02 09:14:58

标签: vector types rust

我正在尝试定义一个自定义结构,其字段可以是std::vec::Vec 任何类型的元素:

use std::vec::Vec;

#[derive(Debug, PartialEq)]
pub struct BertDictionary {
    data: Vec<(Any, Any)>  // not work also with Vec<(_, _)>
}

编译时,会生成E0308 error,这意味着编译器无法推断具体类型。有可能定义这样的结构吗?

例如,当每个元素可以表示为(name, "user"), (id, 1)等时,我将使用此向量。

1 个答案:

答案 0 :(得分:2)

Any是一个特征,而不是具体类型,因此您需要在结构中添加泛型类型参数。

struct BertDirectory<T: Any> {
    data: Vec<T>
}

您可能还希望确保T也是实现DebugPartialEq的内容。这不是编译所必需的,但如果您想确保BertDirectory始终实现这些特征,那就是这样。否则,只有在Debug这样做时才会实施T

struct BertDirectory<T: Any + Debug + PartialEq> {
    data: Vec<T>
}

即使给出了这两件事,我也不知道这会给你你真正想要的东西,因为data仍然会被限制为持有单一类型T只能表示每个结构实例的单个类型。

如果您需要data来存储不同类型的值,您可能会想要使用trait objects代替,这是Rust使用vTables的方式:

pub trait MyTrait: Debug {
    // you can still use Any by doing MyTrait: Any + Debug
    // Note that you won't be able to derive PartialEq for your trait 
    // because PartialEq can't be made into a TraitObject

    // can also define whatever methods you would want on your data, which
    // might be preferable to using Any, if possible
}

pub struct BertDirectory<T: MyTrait>{
    data: Vec<(Box<MyTrait>, Box<MyTrait>)>
}

这样,在编译时不需要知道T的具体类型。 data中的每个元素可以是不同的具体类型,并且将自动调用正确的方法。但是,你无法派生PartialEq,所以你必须自己实现它。