Rust 绑定模式匹配
示例
可以使用@以下方式将值绑定到名称:
struct Badger { pub age: u8 } fn main() { //让我们创建一个Badger实例 let badger_john = Badger { age: 8 }; //现在,根据他的年龄,找出约翰最喜欢的活动是什么 match badger_john.age { //我们可以将值范围绑定到变量并在匹配的分支中使用它们 baby_age @ 0...1 => println!("John is {} years old, he sleeps a lot", baby_age), young_age @ 2...4 => println!("John is {} years old, he plays all day", young_age), adult_age @ 5...10 => println!("John is {} years old, he eats honey most of the time", adult_age), old_age => println!("John is {} years old, he mostly reads newspapers", old_age), } }
这将打印:
John is 8 years old, he eats honey most of the time