Collect Then Mutate Two Phase Borrows

When a mutation needs data from the same collection, first collect targets by shared borrow, then mutate after collect ends the borrow.

RustData Integrity

Code

rustsnippet
38 lines
struct Room {
    name: String,
    occupied: bool,
}

fn main() {
    let mut rooms = vec![
        Room { name: "a1".into(), occupied: true },
        Room { name: "b2".into(), occupied: false },
        Room { name: "c3".into(), occupied: true },
        Room { name: "d4".into(), occupied: false },
    ];

    // 边遍历边改借不到:&rooms 的共享借用还没结束就要可变借用,
    // 编译器拒绝(取消注释无法编译)
    // for room in &rooms { rooms.pop(); }

    // 两阶段:先用共享借用收集目标下标,collect 结束借用即结束
    let free: Vec<usize> = rooms
        .iter()
        .enumerate()
        .filter(|(_, room)| !room.occupied)
        .map(|(index, _)| index)
        .collect();
    println!("targets: {free:?}");

    // 再用可变访问逐个置位,两个阶段互不冲突
    for index in &free {
        rooms[*index].occupied = true;
    }

    let busy: Vec<String> = rooms
        .iter()
        .filter(|room| room.occupied)
        .map(|room| room.name.clone())
        .collect();
    println!("occupied now: {busy:?}");
}

How the snippet works

Collect Then Mutate Two Phase Borrows comes down to the function main.

Repetition is confined to for index in &free — the rest of the file is straight-line.

Applying it

The demo output is labeled (targets:, occupied now:), so every printed line maps back to its originating operation.

Statements that matter

.filter(|(_, room)| !room.occupied)
.map(|(index, _)| index)
.collect();
.map(|room| room.name.clone())
.collect();

Interactive Tools for This Topic

FAQ

What does Collect Then Mutate Two Phase Borrows print when run?
Run it as a complete program — the output lines carry labels such as `targets:`, `occupied now:`.