Search code examples
rustvariant

How to create variants in Rust


I'm a newbie in Rust.

How can I achieve the same thing as below in Rust?

// C++ code
variant<string, int, float> value;

Update

I am creating a scanner (lexer if you prefer it) in rust. And I want to store a literal that varies (maybe a string, an integer, etc.) to each Token struct.


Solution

  • Without knowing specific requirements, the most natural way to achieve that is with enums. The Rust enum construct can have members that match various types. See this chapter of the Rust book for how to define enums, then how to deconstruct (pattern match) them to get at the data inside: 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);
        }
    }