Reputation:
I have an enum:
pub enum Enum1 {
A(String),
B(i64),
C(f64)
}
How can I do pattern matching against A? That is, I want to get its String value. I've tried this:
match optionMyEnum {
Some(A(x: String)) => ...
and got plenty of the compile errors.
Upvotes: 0
Views: 493
Reputation: 430300
The Rust Programming Language has an entire section on matching. I'd highly encourage you to read that section (and the entire book). A lot of time and effort has gone into that documentation.
You simply specify a name to bind against. There's no need to write out types:
pub enum Enum {
A(String),
B(i64),
C(f64),
}
fn main() {
let val = Enum::A("hello".to_string());
match val {
Enum::A(x) => println!("{}", x),
_ => println!("other"),
}
}
In many cases, you will want to bind to a reference to the values:
Enum::A(ref x) => println!("{}", x),
Upvotes: 4