如何在 Rust 中创建变体

bic*_*nna 2 variant rust

我是 Rust 的新手。

我怎样才能在 Rust 中实现与下面相同的效果?

// C++ code
variant<string, int, float> value;
Run Code Online (Sandbox Code Playgroud)

更新

我正在用 Rust 创建一个扫描仪(如果你喜欢的话,可以使用词法分析器)。我想存储每个 Token 结构都不同的文字(可能是字符串、整数等)。

pio*_*ojo 6

在不知道具体要求的情况下,实现这一目标的最自然的方法是使用枚举。Rust 枚举构造可以具有匹配各种类型的成员。请参阅 Rust 书的这一章,了解如何定义枚举,以及如何解构(模式匹配)它们以获取内部数据: https: //doc.rust-lang.org/book/ch06-00-enums.html

enum Value {
    Msg(String),
    Count(u32),
    Temperature(f32),
}

pub fn value_test() {
    let value = Value::Count(7);
    // the type is Value, so it could be Value::Count(_), Value::Temperature(_),
    // or Value::Msg(_), or you could even add a Value::Empty definition
    // that has nothing inside. Or a struct-type with member variables.
    if let Value::Msg(inner_str) = value {
        println!("This will not run: {}", inner_str);
    }
}
Run Code Online (Sandbox Code Playgroud)