fn main() {
let x = 8; // 定义 x
match x {
0 => println!("零"),
1|2|3=> println!(" 1 or 2 or 3"),
4..=6 => println!("4-6"),
n => println!("其他数字: {}", n),
}
let tuple = (1, 2, 3,4);
match tuple {
(1, 2,..) => println!("第一个是 1"),
_ => (),
}
let arr = [1, 2, 3];
match arr {
[0, _, _] => println!("第一个是 0"),
[a, b, c] => println!("{},{},{}", a, b, c),
_ => (),
}
let point = (10, 20);
match point {
(0, 0) => println!("原点"),
(x, 0) => println!("x 轴: {}", x),
(0, y) => println!("y 轴: {}", y),
(x, y) => println!("坐标: ({}, {})", x, y),
}
#[derive(Debug)]
struct Point { x: i32, y: i32 }
let p1 = Point { x: 0, y: 0 };
match p1 {
Point { x: 0, y: 0 } => println!("原点"),
Point { x, y } if x == y => println!("对角线"),
Point { x, y } => println!("({}, {})", x, y),
}
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(u8, u8, u8),
}
let msg = Message::Move { x: 10, y: 20 };
match msg {
Message::Quit => println!("退出"),
Message::Move { x, y } => println!("移动到 ({}, {})", x, y),
Message::Write(text) => println!("消息: {}", text),
Message::ChangeColor(r, g, b) => println!("RGB: {},{},{}", r, g, b),
}
let num = &Some(5);
match num {
&Some(x) => println!("解引用后: {}", x), // 直接取值
// 或者
Some(ref x) => println!("借用: {}", x), // ref 表示引用
None => (),
}
match x {
7 | 8 if x % 2 == 0 => println!("7 或 8 且为偶数"),
n if n < 0 => println!("负数"),
n if n == 0 => println!("零"),
n if n > 0 => println!("正数"),
_ => (),
}
//所有分支必须返回相同类型:
let result = match x {
0 => "零".to_string(),
n => format!("其他: {}", n),
};
println!("{}", result);
//绑定运算符 @
match x {
n @ 1..=5 => println!("1~5: {}", n),
n @ 6..=10 => println!("6~10: {}", n),
_ => println!("其他"),
}
match p1 {
p @ Point { x: 0, y: 0 } => println!("原点: {:?}", p),
_ => (),
}
if let Some(value) = Some(5){ //if let Some(value) = Option::<i32>::None
println!("有值: {}", value);
} else {
println!("无值");
}
let result: Result<i32, &str> = Err("error");
if let Ok(value) = result {
println!("成功: {}", value);
} else {
println!("失败");
}
let mut stack = vec![1, 2, 3, 4, 5];
while let Some(top) = stack.pop() {
println!("弹出: {}", top);// 输出:5 4 3 2 1
}
}
//实战综合示例
use std::fs::File;
use std::io::Read;
fn main() {
// 处理 Option
let ages: Vec<Option<i32>> = vec![Some(10), None, Some(25)];
for age in ages {
if let Some(age) = age {
if age < 18 {
println!("未成年: {}", age);
} else {
println!("成年: {}", age);
}
} else {
println!("年龄未知");
}
}
// 处理 Result
let mut file = File::open("test.txt");
if let Ok(mut f) = file {
let mut content = String::new();
if let Ok(_) = f.read_to_string(&mut content) {
println!("文件内容: {}", content);
} else {
println!("读取失败");
}
} else {
println!("文件不存在");
}
// 枚举匹配
#[derive(Debug)]
enum UserAction {
Create(String),
Delete(i32),
Update { id: i32, name: String },
}
let action = UserAction::Create("Alice".to_string());
if let UserAction::Create(name) = action {
println!("创建用户: {}", name);
}
}