Rust结构体、枚举与模式匹配实战
3 阅读
预计 3 分钟
Rust的结构体和枚举比其他语言更强大,配合模式匹配可以优雅地处理复杂数据。
## 结构体
```rust
#[derive(Debug)]
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
impl User {
fn new(username: String, email: String) -> Self {
Self {
username,
email,
sign_in_count: 0,
active: true,
}
}
fn summary(&self) -> String {
format!("{} ({}) - {} visits", self.username, self.email, self.sign_in_count)
}
}
```
## 元组结构体与单元结构体
```rust
struct Color(i32, i32, i32);
struct AlwaysEqual;
```
## 枚举
Rust枚举可以携带数据:
```rust
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
impl Message {
fn process(&self) {
match self {
Message::Quit => println!("Quit"),
Message::Move { x, y } => println!("Move to ({}, {})", x, y),
Message::Write(text) => println!("Write: {}", text),
Message::ChangeColor(r, g, b) => println!("Color: ({}, {}, {})", r, g, b),
}
}
}
```
## 模式匹配
```rust
let value = Some(7);
match value {
Some(1) => println!("one"),
Some(2..=5) => println!("two to five"),
Some(n) if n > 10 => println!("big: {}", n),
Some(_) => println!("other"),
None => println!("none"),
}
if let Some(n) = value {
println!("Got: {}", n);
}
```
Rust的枚举和模式匹配组合是表达业务逻辑的利器,比传统的继承体系更灵活。
0 条评论 欢迎参与讨论