Match On References Without Moving

Match against references and destructure through them so borrowed data stays in place, with bindings that keep ownership at the owner.

RustData Integrity

Code

rustsnippet
36 lines
#[derive(Debug)]
enum Shape {
    Circle { radius: f64 },
    Rect { w: f64, h: f64 },
}

// 接 &Shape:match 直接对引用解构,不移动任何字段
fn area(shape: &Shape) -> f64 {
    match shape {
        // 借用模式下 radius/w/h 都是 &f64,解引用即可计算
        Shape::Circle { radius } => std::f64::consts::PI * radius * radius,
        Shape::Rect { w, h } => w * h,
    }
}

fn main() {
    let shapes = vec![
        Shape::Circle { radius: 1.0 },
        Shape::Rect { w: 3.0, h: 4.0 },
    ];

    for s in &shapes {
        // s 是 &Shape,分支绑定同样是引用(match ergonomics)
        match s {
            Shape::Circle { radius } => println!("circle r={radius} area={:.3}", area(s)),
            Shape::Rect { w, h } => println!("rect {w}x{h} area={}", area(s)),
        }
    }

    // 需要改值时对 &mut 匹配:绑定变为 &mut f64
    let mut rect = Shape::Rect { w: 2.0, h: 2.0 };
    if let Shape::Rect { w, h } = &mut rect {
        *w = 10.0;
        println!("mutated: {rect:?}");
    }
}

How the snippet works

Count the functions area and main as the entire surface area of Match On References Without Moving.

Repetition is confined to for s in &shapes — the rest of the file is straight-line. Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.

Applying it

Entry signature: fn area(shape: &Shape) -> f64

Look for the circle r=, rect, mutated: prefixes when the file runs; they tie each line to its step.

main calls 1 helper in sequence: area.

Statements that matter

fn area(shape: &Shape) -> f64 {
    match shape {
        // 借用模式下 radius/w/h 都是 &f64,解引用即可计算
        Shape::Circle { radius } => std::f64::consts::PI * radius * radius,
        Shape::Rect { w, h } => w * h,
    }
}

Interactive Tools for This Topic

FAQ

What does Match On References Without Moving print when run?
Run it as a complete program — the output lines carry labels such as `circle r=`, `rect`, `mutated:`.