Underscore Ignores Unused Match Parts

Use _ and _binding to silence parts of a pattern: _ never binds, _x binds without moving, so borrowed fields stay borrowable.

RustData Integrity

Code

rustsnippet
34 lines
struct Message {
        id: u32,
        sender: String,
        payload: String,
    }

    fn main() {
        let msg = Message {
            id: 1,
            sender: "alice".into(),
            payload: "deploy ready".into(),
        };

        // _ 不绑定也不 move:sender/payload 原地保留
        let Message { id, .. } = &msg;
        println!("id {id} (rest untouched)");

        // _sender 绑定但不 move,payload 仍可读
        let Message { id, sender: _sender, payload } = &msg;
        println!("id {id}, from {_sender}, payload {payload}");

        // 按值匹配:_ 不拿所有权,整包仍可用
        let Message { id: _, sender, payload } = msg;
        println!("owned sender {sender}, payload {payload}");

        // 匹配臂内丢弃不需要的变体载荷
        let code = 404;
        let class = match code {
            200..=299 => "success",
            404 => "not found",
            _ => "other", // _ 兜底其余一切
        };
        println!("{code} -> {class}");
    }

What the code does

The working surface is the function main — everything else is wiring.

Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.

Points of care

  • The import surface (if any) is all standard library, all versioned with the language itself.

Applying it

The entry-point signature is fn main()

Expect labeled output — id, owned sender — when the file runs.

Statements that matter

let class = match code {
    200..=299 => "success",
    404 => "not found",
    _ => "other", // _ 兜底其余一切
};

Interactive Tools for This Topic

FAQ

What does Underscore Ignores Unused Match Parts print when run?
Invoke the file as-is — the `id`, `owned sender` prefixes identify which step printed each line.