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:
to_string()
methodOperator
. I think the second is the preferred choice, though I don't know if creating a vector of references will introduce lots of complexity.
答案 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
将它们拿出来。