Hello,
I want to build a VM and have the commands represented as enums. Some commands should load constants so I have this. When I execute commands how can I unwrap the i32 from OpConstant?
enum OpCode {
OpConstant(i32),
OpReturn,
....
}
Hello,
I want to build a VM and have the commands represented as enums. Some commands should load constants so I have this. When I execute commands how can I unwrap the i32 from OpConstant?
enum OpCode {
OpConstant(i32),
OpReturn,
....
}
thanks for your answer. but what I was looking for is not covered in there. right now I would solve it like this - extracting the value of an enum. But surely there must be a more elegant way?
enum TestEnum {
One(i32),
Two
}
fn main() {
let test = TestEnum::One(21);
let mut int = 0;
match test {
TestEnum::One(i) => int = i,
TestEnum::Two => println!("enum Two")
}
println!("{}", int);
}
Have you looked at if let
and let else
?
These might be a little more succinct if you only care about the one pattern/value
You can write it in one line if you want.
let int = if let TestEnum::One(i) = test { i } else { 0 };
If you are using this functionality a lot, I recommend write a function like this.
impl TestEnum {
fn extract_one(&self) -> Option<i32> {
if let TestEnum::One(i) = self { Some(*i) } else { None }
}
}
thanks this is what I am looking for. But why do you write Some(*i)
instead of Some(i)
?
It is covered there, in the section for the link I sent:
https://doc.rust-lang.org/book/ch06-03-if-let.html
You have to do a pattern match of some kind to extract data from an enum variant.
When you match on a reference, a variable in the pattern will also be a reference.
The code above is matching on self
, which is a reference. Therefore, the variable in the pattern, i
, is also a reference, it is type &i32
. So when creating the return value, Option<i32>
, i
must be dereferenced to give an i32
. This is why Some(*i)
is used.
There are ways to create patterns where, instead of dereferencing the variable after matching, the dereferencing can be done in the pattern. But I suggest first learning the basics of pattern matching. The book has a whole chapter on it: Patterns and Matching. Pattern matching is a big part of Rust, and you can learn it a little at a time. But please do check the book for answers.