Rc Try Unwrap Reclaims Value

Call Rc::try_unwrap while other handles exist to see the error path, drop them, then reclaim the inner String without cloning.

RustData Integrity

Code

rustsnippet
24 lines
use std::rc::Rc;

fn main() {
    let shared = Rc::new(String::from("payload"));
    let clone = Rc::clone(&shared);
    println!("strong count: {}", Rc::strong_count(&shared));

    // an extra handle makes try_unwrap fail instead of stealing the value
    let extra = Rc::clone(&shared);
    match Rc::try_unwrap(extra) {
        Ok(value) => println!("unexpected owner: {value}"),
        Err(rc) => {
            println!("still shared: {}", Rc::strong_count(&rc));
            drop(rc);
        }
    }

    // dropping the clone leaves exactly one owner
    drop(clone);
    println!("after drop: {}", Rc::strong_count(&shared));

    let value = Rc::try_unwrap(shared).unwrap_or_else(|_| String::from("failed"));
    println!("reclaimed: {value}");
}

What the code does

Everything happens inside the function main.

A match spells out every case; omit one and the code does not compile.

Points of care

  • It is dependency-free in the strict sense — the import list, if any, is empty of packages.

Using it

The main signature reads fn main()

Output lines are prefixed (strong count:, unexpected owner:, still shared:), making each step’s effect easy to spot.

Key statements

match Rc::try_unwrap(extra) {
Ok(value) => println!("unexpected owner: {value}"),
Err(rc) => {
println!("still shared: {}", Rc::strong_count(&rc));
drop(rc);
}
}
let value = Rc::try_unwrap(shared).unwrap_or_else(|_| String::from("failed"));

Interactive Tools for This Topic

FAQ

What does Rc Try Unwrap Reclaims Value print when run?
No setup needed: run the file and look for labeled lines like `strong count:`, `unexpected owner:`, `still shared:` in the output.