1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
| use std::collections::HashMap;
use std::error::Error;
use std::fmt;
use serde::{Deserialize, Serialize};
use tokio::time::{sleep, Duration};
// 自定义错误类型
#[derive(Debug)]
enum AppError {
NotFound(String),
Validation(String),
}
impl fmt::Display for AppError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AppError::NotFound(msg) => write!(f, "Not found: {}", msg),
AppError::Validation(msg) => write!(f, "Validation error: {}", msg),
}
}
}
impl Error for AppError {}
// 用户结构体
#[derive(Debug, Clone, Serialize, Deserialize)]
struct User {
id: u32,
name: String,
email: String,
age: Option<u8>,
}
impl User {
// 关联函数
fn new(id: u32, name: String, email: String, age: Option<u8>) -> Self {
Self { id, name, email, age }
}
// 方法
fn is_adult(&self) -> bool {
self.age.map_or(false, |age| age >= 18)
}
}
// 用户仓库
struct UserRepository {
users: HashMap<u32, User>,
next_id: u32,
}
impl UserRepository {
fn new() -> Self {
Self {
users: HashMap::new(),
next_id: 1,
}
}
fn add_user(&mut self, mut user: User) -> u32 {
user.id = self.next_id;
self.users.insert(self.next_id, user);
self.next_id += 1;
self.next_id - 1
}
fn get_user(&self, id: u32) -> Result<&User, AppError> {
self.users.get(&id)
.ok_or_else(|| AppError::NotFound(format!("User with id {} not found", id)))
}
// 泛型方法示例
fn find_user_by<F>(&self, predicate: F) -> Option<&User>
where
F: Fn(&User) -> bool,
{
self.users.values().find(|&user| predicate(user))
}
}
// 异步示例
async fn process_user_data(user: &User) -> Result<String, Box<dyn Error>> {
// 模拟异步操作
sleep(Duration::from_millis(100)).await;
if user.name.is_empty() {
return Err(Box::new(AppError::Validation("Name cannot be empty".to_string())));
}
Ok(format!("Processed user: {} ({})", user.name, user.email))
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let mut repo = UserRepository::new();
let user1 = User::new(0, "Alice".to_string(), "alice@example.com".to_string(), Some(30));
let id1 = repo.add_user(user1);
let user2 = User::new(0, "Bob".to_string(), "bob@example.com".to_string(), None);
let id2 = repo.add_user(user2);
// 模式匹配
match repo.get_user(id1) {
Ok(user) => {
println!("Found user: {:?}", user);
println!("Is adult? {}", user.is_adult());
// 异步处理
match process_user_data(user).await {
Ok(result) => println!("{}", result),
Err(e) => eprintln!("Error: {}", e),
}
}
Err(e) => eprintln!("Error: {}", e),
}
// 使用迭代器
let adult_users: Vec<_> = repo.users.values()
.filter(|user| user.is_adult())
.collect();
println!("Adult users: {}", adult_users.len());
Ok(())
}
|