.. 忽略模式
什么是 .. 忽略模式
.. 是 Rust 模式匹配中的"忽略剩余"语法,用来跳过你不关心的那些字段或元素。它可以用在元组、结构体和切片的模式中,让你只提取需要的部分而不用为每个字段都写占位符。
rust
fn main() {
// 一个有很多元素的元组
let data = (1, 2, 3, 4, 5);
// 只需要第一个和最后一个
let (first, .., last) = data;
println!("第一个:{},最后一个:{}", first, last); // 1, 5
// 只需要第一个
let (first, ..) = data;
println!("第一个:{}", first); // 1
// 只需要最后一个
let (.., last) = data;
println!("最后一个:{}", last); // 5
}在元组中使用 ..
rust
fn main() {
let tuple = (10, 20, 30, 40, 50);
// 取第一个,忽略其余
let (a, ..) = tuple;
println!("a = {}", a); // 10
// 取最后一个,忽略前面的
let (.., e) = tuple;
println!("e = {}", e); // 50
// 取首尾,忽略中间
let (first, .., last) = tuple;
println!("首:{},尾:{}", first, last); // 10, 50
// 取前两个和最后一个
let (a, b, .., e) = tuple;
println!("a={}, b={}, e={}", a, b, e); // 10, 20, 50
// 在 match 中使用
match tuple {
(1, ..) => println!("以 1 开头"),
(.., 50) => println!("以 50 结尾"), // 匹配这个
_ => println!("其他"),
}
}在结构体中使用 ..
对结构体来说,.. 可以忽略你不关心的字段,不需要逐个写 _。
rust
struct User {
name: String,
age: u32,
email: String,
is_active: bool,
login_count: u64,
}
fn main() {
let user = User {
name: String::from("张三"),
age: 28,
email: String::from("zhangsan@example.com"),
is_active: true,
login_count: 42,
};
// 只关心 name 和 age,忽略其他字段
let User { name, age, .. } = &user;
println!("{},{}岁", name, age);
// 在 match 中忽略不关心的字段
match &user {
User { is_active: true, name, .. } => {
println!("{} 是活跃用户", name);
}
User { is_active: false, name, .. } => {
println!("{} 已停用", name);
}
}
// 对比:不用 .. 的话需要逐个忽略
let User { name: _, age: _, email, is_active: _, login_count: _ } = &user;
println!("邮箱:{}", email);
// 显然 .. 简洁得多
}在切片模式中使用 ..
rust
fn main() {
let numbers = [1, 2, 3, 4, 5, 6, 7];
// 匹配切片的首尾
match numbers.as_slice() {
[first, .., last] => {
println!("首:{},尾:{}", first, last);
}
_ => {}
}
// 匹配前几个元素
match numbers.as_slice() {
[1, 2, 3, ..] => println!("以 1, 2, 3 开头"),
_ => println!("其他"),
}
// 匹配不同长度的切片
let data: &[i32] = &[10, 20];
match data {
[] => println!("空"),
[single] => println!("一个元素:{}", single),
[first, second] => println!("两个元素:{}, {}", first, second),
[first, .., last] => println!("多个元素,首{}尾{}", first, last),
}
// 绑定中间部分到切片
let arr = [1, 2, 3, 4, 5];
match arr.as_slice() {
[first, middle @ .., last] => {
println!("首:{},中间:{:?},尾:{}", first, middle, last);
// 首:1,中间:[2, 3, 4],尾:5
}
_ => {}
}
}_ 和 .. 的区别
| 语法 | 含义 | 使用位置 |
|---|---|---|
_ | 忽略一个值 | 任何模式位置 |
.. | 忽略剩余的多个值 | 元组、结构体、切片模式中 |
_name | 绑定但标记为未使用(不触发警告) | 变量绑定 |
rust
fn main() {
let tuple = (1, 2, 3, 4);
// _ 忽略单个位置
let (a, _, _, d) = tuple;
println!("a={}, d={}", a, d);
// .. 忽略多个位置
let (a, .., d) = tuple;
println!("a={}, d={}", a, d);
// 两种方式结果一样,但 .. 更简洁
// 元素很多时差别更明显:
// let (a, _, _, _, _, _, _, _, _, z) = big_tuple; // 繁琐
// let (a, .., z) = big_tuple; // 简洁
}基本示例
解析简化的 HTTP 请求信息:
rust
struct HttpRequest {
method: String,
path: String,
version: String,
headers: Vec<(String, String)>,
body: Option<String>,
}
fn log_request(req: &HttpRequest) {
// 只关心 method 和 path,忽略其他
let HttpRequest { method, path, .. } = req;
println!("[请求] {} {}", method, path);
}
fn check_content_type(req: &HttpRequest) {
// 只关心 headers
let HttpRequest { headers, .. } = req;
for (key, value) in headers {
if key.to_lowercase() == "content-type" {
println!("Content-Type: {}", value);
return;
}
}
println!("未指定 Content-Type");
}
fn route(req: &HttpRequest) {
// 在 match 中用 .. 忽略不相关的字段
match req {
HttpRequest { method, path, .. } if method == "GET" && path == "/" => {
println!("-> 首页");
}
HttpRequest { method, path, .. } if method == "GET" && path.starts_with("/api") => {
println!("-> API 请求:{}", path);
}
HttpRequest { method, path, .. } if method == "POST" => {
println!("-> POST 到 {}", path);
}
_ => println!("-> 404 Not Found"),
}
}
fn main() {
let req = HttpRequest {
method: String::from("GET"),
path: String::from("/api/users"),
version: String::from("HTTP/1.1"),
headers: vec![
(String::from("Content-Type"), String::from("application/json")),
(String::from("Accept"), String::from("*/*")),
],
body: None,
};
log_request(&req);
check_content_type(&req);
route(&req);
}常见问题
问题一:.. 在一个模式中能出现几次?
只能出现一次。因为如果出现两次,编译器无法确定中间有多少元素属于第一个 .. 和第二个 ..。
rust
fn main() {
let tuple = (1, 2, 3, 4, 5);
// let (a, .., b, .., c) = tuple; // 编译错误:.. 只能出现一次
let (a, .., c) = tuple; // 正确
println!("{}, {}", a, c);
}问题二:.. 可以匹配零个元素吗?
可以。对于两个元素的元组 (1, 2),(a, .., b) 中的 .. 匹配零个元素,a=1,b=2。
问题三:结构体中 .. 必须放在最后吗?
是的。在结构体解构中,.. 必须放在最后面,表示"忽略剩余的所有字段"。
rust
struct Point3D { x: f64, y: f64, z: f64 }
fn main() {
let p = Point3D { x: 1.0, y: 2.0, z: 3.0 };
let Point3D { x, .. } = p; // 正确,.. 在最后
// let Point3D { .., z } = p; // 编译错误
println!("x = {}", x);
}适用场景
- 结构体部分解构:只需要结构体的几个字段时
- 元组首尾提取:只关心元组的第一个或最后一个元素
- 切片模式匹配:匹配切片的开头、结尾或首尾
- 忽略中间部分:配合
@ ..把中间部分绑定为子切片 - 减少冗余:避免为每个不关心的字段写
_
注意事项
..在一个模式中只能出现一次..可以匹配零个或多个元素/字段- 结构体中
..必须放在最后 - 元组和切片中
..可以在开头、中间或末尾 ..不能单独作为整个模式(那就不匹配任何具体的东西了)- 切片中可以用
name @ ..把忽略的部分绑定到一个子切片变量上
总结
.. 是模式匹配中"忽略剩余部分"的语法,用在元组、结构体和切片中。它让你只关注需要的部分,跳过不关心的字段或元素。在结构体中特别实用——字段很多时只写需要的几个加上 .. 就行,不用为每个忽略的字段写 _。.. 在一个模式中只能出现一次,可以匹配零个或多个元素。在切片模式中,还可以用 name @ .. 把忽略的中间部分绑定到一个子切片变量上。