如何在Vec中存储具有不同参数的类型?

时间:2018-03-27 03:39:28

标签: generics rust traits

我试图在Rust中设置树结构,但是我遇到了如何存储节点列表的问题,这些节点存储了不同类型的值,因此具有不同的类型参数

问题的简化版本如下:

struct Node<T> {
    pub props: T,
    pub children: Vec<Node>
}

fn main() {
    let node = Node {
        props: (42, 6),
        children: vec![Node {
            props: Some("potatoes"),
            children: vec![]
        }]
    };
}

无法使用以下错误进行编译:

error[E0243]: wrong number of type arguments: expected 1, found 0
 --> src/main.rs:4:19
  |
4 |     children: Vec<Node>
  |                   ^^^^ expected 1 type argument

我无法提供类型参数,因为它必须被允许为任何东西。这样做的最佳方法是什么?

我查看了this question,但它没有解决类型参数。

2 个答案:

答案 0 :(得分:0)

如果要存储不同类型的值,请首先确定要存储的所有值类型。 然后定义enum

enum Value {
    Pair(i32, i32),
    MayBeStr(Option<&'static str>),
    ... // any value that you would like to store
}

然后把它连接起来:

struct Node {
    pub props: Value,
    pub children: Vec<Node>
}

fn main() {
    let node = Node {
        props: Value::Pair(42, 6),
        children: vec![Node {
            props: Value::MayBeStr(Some("potatoes")),
            children: vec![]
        }]
    };
}

Link to Playground

答案 1 :(得分:0)

到目前为止,我提出的最佳解决方案是为所有项目添加特征并使用Box来存储它们。对于这个例子:

trait Props {}

impl Props for (i32, i32) {}
impl<'a> Props for Option<&'a str> {}

struct Node<'a> {
    pub props: Box<Props + 'a>,
    pub children: Vec<Node<'a>>
}

fn main() {
    let node = Node {
        props: Box::new((42, 6)),
        children: vec![Node {
            props: Box::new(Some("potatoes")),
            children: vec![]
        }]
    };
}
相关问题