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.
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),
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.