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.
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);
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With