向量在 Rust 中存储混合类型的数据 [英] Vector store mixed types of data in Rust

查看:27
本文介绍了向量在 Rust 中存储混合类型的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将中缀表达式转换为后缀表达式的上下文中,使用 Shunting-yard 算法.我想使用一个向量来存储输出,它将同时存储运算符和数字类型的数据.

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

上面的代码当然不能编译,因为 to_string() 方法没有为 Operator 定义.我看到了两种解决方法:

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. 定义一个to_string()方法
  2. 创建一个向量来存储对数字和 Operator 的引用.
  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.

推荐答案

无需使用引用;只需将数字和 Operator 直接存储在枚举中:

There's no need to use references; just store the numbers and Operators directly in an enum:

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.

这篇关于向量在 Rust 中存储混合类型的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆