Rust 枚举与匹配模式¶
1. 枚举¶
枚举是一种用户自定义的数据类型,用于表示具有一组离散可能的变量。合适地使用枚举,能让我们的代码更加严谨,且更易于理解。
在 Rust 中常用的枚举类型为 Option
和 Result
。
Option和Result的使用
2. 匹配模式¶
Rust 中使用 match
关键字进行条件匹配,当 match
独立使用时,也结合 _
、..=
、三元表达式,功能非常强大,示例代码如下:
match使用案例 | |
---|---|
此外,更多场景下,通常我们会匹配和枚举一起使用。
枚举和匹配的使用
enum BuildingLocation {
Number(i32),
Name(String), // 不用 &str
Unknown, // 其他未知信息
}
impl BuildingLocation {
fn print_location(&self) {
match self {
// BuildingLocation::Number(44)
BuildingLocation::Number(c) => println!("Building Number: {}", c),
// BuildingLocation::Name("ok".to_string())
BuildingLocation::Name(c) => println!("Building Name: {}", c),
BuildingLocation::Unknown => println!("Unknown"),
}
}
}
fn main() {
let house_name = BuildingLocation::Name("abc".to_string());
let house_number = BuildingLocation::Number(100);
let house_unknown = BuildingLocation::Unknown;
house_name.print_location();
house_num.print_location();
}