Vector store mixed types of data in Rust

时间:2016-11-12 05:36:36

标签: vector type-conversion rust

In the context of converting a infix expression to a postfix one, using the Shunting-yard algorithm. I want to use a vector to store the output, which would store both operator and numeric type data.

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Operator {
    Add,
    Sub,
    Mul,
    Div,
}

fn main() {
    let mut output: Vec<String> = Vec::new();  // create an output vector
    let a = 2;
    let b = Operator::Add;
    let c = 3;
    output.push(a.to_string());
    output.push(b.to_string());
    output.push(c.to_string());
}

This above code of course doesn't compile, since the to_string() method is not defined for Operator. I see two ways to fix it:

  1. Define a to_string() method
  2. Create a vector to store references to numbers and Operator.

I think the second is the preferred choice, though I don't know if creating a vector of references will introduce lots of complexity.

1 个答案:

答案 0 :(得分:7)

没有必要使用参考文献;只需将数字和Operator直接存储在枚举中:

enum Thing {
    Op(Operator),
    Number(i32),
}

fn main() {
    let mut output: Vec<Thing> = Vec::new();
    let a = 2;
    let b = Operator::Add;
    let c = 3;
    output.push(Thing::Number(a));
    output.push(Thing::Op(b));
    output.push(Thing::Number(c));
}

然后match将它们拿出来。