[英]A pattern matching against a constructor of an enum
I have an enum: 我有一个枚举:
pub enum Enum1 {
A(String),
B(i64),
C(f64)
}
How can I do pattern matching against A? 如何针对A模式匹配? That is, I want to get its String value. 也就是说,我要获取其String值。 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 . Rust编程语言完整介绍了match 。 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),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.