Arc make_mut Clones Only When Shared

Arc::make_mut clones the shared value only while other owners hold references, then mutates in place once the Arc is uniquely owned.

RustData Integrity

Code

rustsnippet
32 lines
use std::sync::Arc;

#[derive(Debug)]
struct Route {
    path: String,
    weight: u32,
}

fn main() {
    let mut shared: Arc<Vec<Route>> = Arc::new(vec![
        Route { path: "/health".into(), weight: 1 },
        Route { path: "/api".into(), weight: 5 },
    ]);

    let reader = Arc::clone(&shared);
    println!("strong count before write: {}", Arc::strong_count(&shared));

    // Other owners still exist: make_mut clones the whole Vec first, then hands out an exclusive &mut
    let writer = Arc::make_mut(&mut shared);
    writer.push(Route { path: "/metrics".into(), weight: 2 });
    writer[0].weight = 3;

    // The clone happens before the borrow: reader still sees the old snapshot
    println!("reader sees {} routes, first weight {}", reader.len(), reader[0].weight);
    println!("owner sees {} routes, first weight {}", shared.len(), shared[0].weight);

    // Now a single owner remains: make_mut writes in place without cloning
    let writer = Arc::make_mut(&mut shared);
    writer[1].weight = 9;
    println!("strong count after clone-away: {}", Arc::strong_count(&shared));
    println!("{:?}", shared);
}

How it works

Count the function main as the entire surface area of Arc make_mut Clones Only When Shared.

Applying it

The main signature reads fn main()

Running the file prints labeled results such as strong count before write:, reader sees, owner sees — each operation’s effect is visible in the output.

Statements that matter

writer.push(Route { path: "/metrics".into(), weight: 2 });
let writer = Arc::make_mut(&mut shared);
let reader = Arc::clone(&shared);

Interactive Tools for This Topic

FAQ

What does Arc make_mut Clones Only When Shared print when run?
Run it as a complete program — the output lines carry labels such as `strong count before write:`, `reader sees`, `owner sees`.