skip to content

In Rust, when does `Rc::make_mut` clone the inner value, and how do `Rc::get_mut`, `Rc::try_unwrap` and `Rc::unwrap_or_clone` behave differently?

level: seniorimportance: should knowfreq 32%

answer

  1. uniqueness decides everything
  2. other strong handles force a clone
  3. only Weaks left: value moves, Weaks die
  4. get_mut never clones, returns Option
  5. try_unwrap gives the Rc back on Err

basics

~20 s

Rc::make_mut clones the value only when another strong Rc exists; with only Weak handles left it moves the value and those Weaks stop upgrading. Rc::get_mut never clones and returns None if shared; try_unwrap returns Err(rc) unless unique; unwrap_or_clone clones when shared.

solid answer

~40 s

All four answer the same question, whether this handle is the only owner, and differ in what they do when it is not. `Rc::get_mut` returns `Some(&mut T)` only when there is one strong handle and no `Weak`; otherwise `None`, never a clone. `Rc::make_mut` always returns `&mut T`: with other strong handles it clones `T` into a new allocation (clone-on-write, the others keep the old value); with only `Weak` handles left it moves the value into a new allocation without cloning, so those `Weak`s upgrade to `None` from then on. `Rc::try_unwrap` moves `T` out when the strong count is 1, even with `Weak`s outstanding, and otherwise returns `Err(rc)` intact. `Rc::unwrap_or_clone` moves `T` out when unique and clones it otherwise.

code

rust · 24 lines
rust
use std::rc::Rc;

fn main() {
    let mut snapshot = Rc::new(vec![10, 20]);
    let watcher = Rc::downgrade(&snapshot);

    Rc::make_mut(&mut snapshot).push(30); // unique: no clone, Weak detached
    println!("after first make_mut: watcher alive = {}", watcher.upgrade().is_some());

    let undo = Rc::clone(&snapshot);
    Rc::make_mut(&mut snapshot).push(40); // shared: clones the Vec
    println!("snapshot = {:?}, undo = {:?}", snapshot, undo);
    println!("same allocation: {}", Rc::ptr_eq(&snapshot, &undo));

    let weak_undo = Rc::downgrade(&undo);
    match Rc::try_unwrap(undo) {
        Ok(v) => println!("try_unwrap moved out {:?}; weak alive = {}", v, weak_undo.upgrade().is_some()),
        Err(_) => println!("still shared"),
    }

    let other = Rc::clone(&snapshot);
    let copy = Rc::unwrap_or_clone(snapshot); // two strong: clones
    println!("unwrap_or_clone = {:?}, other still = {:?}", copy, other);
}

go deeper

for a junior

Recall that an Rc gives only shared access, and that make_mut and get_mut are the standard ways to get a mutable reference out of one: the first clones when it must, the second refuses.

for a middle

Explain the three branches of make_mut, why get_mut refuses when Weak handles exist, and what try_unwrap returns on success and failure.

for a senior

Diagnose a hidden deep copy caused by an extra strong handle, and Weak observers that go dead after make_mut, and pick the function whose failure mode fits the call site.

for a principal

Judge when clone-on-write snapshots through make_mut are a sound basis for undo or versioned state, against a persistent data structure or explicit diffs whose copy cost does not depend on stray handles.

## Why these functions exist An `Rc<T>` only hands out `&T`: writing `*rc += 1` fails with E0594 (cannot assign to data in an `Rc`). That is the price of shared ownership, since another handle may be reading the same value. But a handle is often **unique at run time**, for example the last snapshot in an undo stack or a value just built and not yet shared. `Rc` offers four associated functions that check the counts and then either mutate in place, copy, move out, or refuse. | Function | Returns | Unique (1 strong, 0 weak) | Other strong handles | 1 strong, some `Weak`s | |---|---|---|---|---| | `Rc::get_mut(&mut rc)` | `Option<&mut T>` | `Some`, in place | `None` | `None` | | `Rc::make_mut(&mut rc)` | `&mut T` | in place | clones `T` into a new allocation | moves `T` to a new allocation, `Weak`s detached | | `Rc::try_unwrap(rc)` | `Result<T, Rc<T>>` | `Ok(T)` | `Err(rc)` | `Ok(T)`, `Weak`s then upgrade to `None` | | `Rc::into_inner(rc)` | `Option<T>` | `Some(T)` | `None`, handle dropped | `Some(T)` | | `Rc::unwrap_or_clone(rc)` | `T` | moves out | clones `T` | moves out | ## `Rc::make_mut`: clone-on-write with a sharp edge `make_mut` is Rust's built-in **clone-on-write** for shared data. The std source runs three branches: 1. **Other strong handles exist**: the value is cloned into a fresh allocation and `rc` is repointed at it. The other handles keep the old value; this handle now owns a private copy. 2. **No other strong handles, but `Weak`s exist**: the value is moved, byte for byte, into a fresh allocation without calling `clone`, and the old allocation is left with zero strong handles. The docs call this disassociating the `Weak` pointers: every existing `Weak` now upgrades to `None`. 3. **Fully unique**: it returns `&mut T` into the existing allocation. Besides any `T: Clone`, the bound also accepts unsized slices and `str`, so `Rc<str>` and `Rc<[T]>` work too. Two consequences matter in real code: - **A silent full copy.** An undo stack that keeps an `Rc` to the previous snapshot makes the next `make_mut` clone the whole document. That is the intended trade, but a stray clone held in a cache or a closure turns every edit into a deep copy. - **Observers going dead.** A `Weak` registered as an observer of a settings object stops upgrading after the owner calls `make_mut`, even though an `Rc` to the settings is alive: it now points at a different allocation. If observers must survive edits, mutate through interior mutability instead. ## `Rc::get_mut`: the strict version `get_mut` checks for one strong handle **and** no `Weak` handles, and returns `None` otherwise. It never clones and never detaches anything, so it suits code that wants to fail loudly, or fall back, rather than pay for a copy. It also works for types that are not `Clone`. ## Moving the value out: `try_unwrap`, `into_inner`, `unwrap_or_clone` - `Rc::try_unwrap(rc)` succeeds when the strong count is 1. Outstanding `Weak`s do not block it; the docs say so explicitly, and afterwards they upgrade to `None`. On failure you get the same `Rc` back in `Err`, so nothing is lost. - `Rc::into_inner(rc)` is `try_unwrap(rc).ok()`: on failure it drops your handle. Called on every clone in turn, exactly one call returns the value. - `Rc::unwrap_or_clone(rc)` never fails: it moves the value out when it can and otherwise clones it, which is the cheapest way to get an owned `T` from a handle you are done with. ## Choosing among them - Need to edit and a copy is acceptable: `make_mut`. - Need to edit only if unique, otherwise take another path: `get_mut`. - Done with the `Rc` and need an owned `T`: `unwrap_or_clone`, or `try_unwrap` when a clone would be wrong. - Shared mutation that every handle must see: none of these; that is interior mutability. A quick way to keep them apart in an interview: `get_mut` and `try_unwrap` **report** sharing to you (`None`, `Err`), while `make_mut` and `unwrap_or_clone` **resolve** it for you by cloning. The first pair never allocates; the second pair may copy the whole value, and `make_mut` may also cut `Weak` handles loose. When you read code that calls `make_mut` in a loop, check that nothing takes another strong handle on each pass, such as an undo snapshot, or every pass pays for a full clone.

  • Why does `Rc::try_unwrap` return `Result<T, Rc<T>>` instead of `Option<T>`?
    So a failed attempt costs nothing. When another strong handle exists, you get your `Rc` back in `Err` and can keep using it, retry later or fall back to cloning. `Rc::into_inner` is the `Option` form, and it drops your handle on failure, which suits code that is releasing handles one by one.
  • Your profiler shows `Vec::clone` inside `Rc::make_mut` on every keystroke of an editor; what do you look for?
    Another strong handle to the same document that lives across the edit: an undo snapshot taken too eagerly, a clone captured by a closure or cached in a view. Print `Rc::strong_count` before the call; above 1 means every `make_mut` clones. Drop or downgrade the extra holder, or snapshot less often.

  • Rc::make_mut returns None when the value is shared.
  • Outstanding Weak handles make Rc::try_unwrap fail.
  • Rc::make_mut mutates the shared value so every handle sees it.
  • Rc::get_mut clones the value when other handles exist.
  • After make_mut, existing Weak handles still reach the edited value.