ref Patterns Borrow Fields Instead Of Moving

Bind struct fields with ref and ref mut so a pattern borrows in place instead of moving values out, then compare that with borrowing the scrutinee up front.

RustData Integrity

Code

rustsnippet
37 lines
#[derive(Debug)]
struct Job {
    id: u32,
    payload: String,
}

fn main() {
    let job = Job {
        id: 7,
        payload: String::from("compress"),
    };

    // ref 绑定:借出 payload,job 没有被部分移动,后面仍能整体使用
    let Job { id, ref payload } = job;
    println!("job {id} payload {payload}");
    println!("job still whole: {job:?}");

    // ref mut 绑定:就地改字段,不取得所有权
    let mut pending = Job {
        id: 8,
        payload: String::from("index"),
    };
    match pending {
        Job { ref mut payload, .. } => payload.push_str("-done"),
    }
    println!("pending after match: {pending:?}");

    // 等价写法:在匹配对象前加 &,绑定模式按 match ergonomics 自动借用
    match &pending.payload {
        name if name.ends_with("-done") => println!("{name} is finished"),
        name => println!("{name} is queued"),
    }

    // 用完之后 pending 仍可移动,因为上面全是借用
    let taken = pending;
    println!("moved out later: {taken:?}");
}

Inside the snippet

The snippet is organized around the function main.

A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

What to watch for

  • Dependency-free by construction — no registry, no lockfile entry.

Using it

Signature: fn main()

Each run prints the 4 labeled blocks job, job still whole:, pending after match:, moved out later: in source order.

Key statements

match &pending.payload {
name if name.ends_with("-done") => println!("{name} is finished"),
name => println!("{name} is queued"),
}
match pending {
Job { ref mut payload, .. } => payload.push_str("-done"),
}

Interactive Tools for This Topic

FAQ

What does ref Patterns Borrow Fields Instead Of Moving print when run?
Running the file directly is enough — expect labeled output lines such as `job`, `job still whole:`, `pending after match:`.