元组解构:

struct Point {
    x: i32,
    y: i32,
}

fn print_point(Point { x, y }: Point) {
    println!("Point coordinates: ({}, {})", x, y);
}

let p = Point { x: 10, y: 20 };
print_point(p); // Point coordinates: (10, 20)

结构体解构

struct Point {
    x: i32,
    y: i32,
}

fn print_point(Point { x, y }: Point) {
    println!("Point coordinates: ({}, {})", x, y);
}

let p = Point { x: 10, y: 20 };
print_point(p); // Point coordinates: (10, 20)

枚举解构:

enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

fn process_message(msg: Message) {
    match msg {
        Message::Quit => println!("Quit"),
        Message::Move { x, y } => println!("Move to x = {}, y = {}", x, y),
        Message::Write(text) => println!("Text message: {}", text),
        Message::ChangeColor(r, g, b) => println!("Change color to ({} ,{} ,{})", r, g, b),
    }
}

let msg = Message::Move { x: 10, y: 20 };
process_message(msg); // Move to x = 10, y = 20

闭包中的解构模式:

let points = vec![(0, 0), (1, 2), (3, 4)];

let distances: Vec<i32> = points.into_iter().map(|(x, y)| x + y).collect();
println!("{:?}", distances); // [0, 3, 7]

捕获引用的闭包参数中的解构
使用 & 符号来模式匹配引用类型的闭包参数。

let numbers = vec![1, 2, 3];
let sum: i32 = numbers.iter().map(|&i| i * 2).sum();
println!("{}", sum); // 12

捕获部分数据
你可以只解构某部分数据,而忽略其他部分。

fn print_y(Point { y, .. }: Point) {
    println!("y = {}", y);
}

struct Point {
    x: i32,
    y: i32,
}

let origin = Point { x: 0, y: 0 };
print_y(origin); // y = 0

匹配一个范围内的值:

let x = 5;
match x {
    1..=5 => println!("x is between 1 and 5"),
    _ => println!("x is out of range"),
}

通配符模式(Wildcard Patterns)

let point = (3, 4);
match point {
    (x, _) => println!("The x-coordinate is {}", x),  // 忽略 y-coordinate
}

putao
8 声望1 粉丝

推动世界向前发展,改善民生。