Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create variants in Rust

Tags:

rust

variant

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.

like image 581
bichanna Avatar asked Jan 31 '26 02:01

bichanna


2 Answers

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);
    }
}
like image 54
piojo Avatar answered Feb 02 '26 22:02

piojo


I wanted to reiterate what @piojo has said about using enums, and also include a crafty example about how you could work with variants in rust code.

enum Action{
    Speak(String),
    Quit,
    RunFunc(i32, i32, fn(i32,i32)->i32),
}

fn act(action: &Action) {
    match action {
        Action::Speak(value) => {
            println!("Asked to speak: {value}");
        },
        Action::Quit => {
            println!("Asked to quit!");
        },
        Action::RunFunc(v1, v2, func) => {
            let res = func(*v1, *v2);
            println!("v1 : {v1}, v2: {v2}, res: {res}");
        }
    }
}

fn main(){
    let action = Action::Speak(String::from("Hello"));
    let action2 = Action::Quit;

    fn add(v1:i32, v2:i32)->i32{
        v1 + v2
    }
    let action3 = Action::RunFunc(5, 6, add);

    act(&action);
    act(&action2);
    act(&action3)
}

Output:

Asked to speak: Hello
Asked to quit!
v1 : 5, v2: 6, res: 11
like image 22
Nico Bako Avatar answered Feb 03 '26 00:02

Nico Bako



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!