std-method

Rust Rc::try_unwrap

Recover ownership of the payload if the handle is the last strong owner. Weak observers do not prevent extraction. If more strong handles remain, Err returns the original handle so you can keep using it. Expected output (not executed): A12 Why: The first attempt retains the Rc; the second extracts its String after the other owner is gone. Common mistake: Discarding Err and unintentionally losing an owning handle.

Formal Syntax & Structure

rust syntaxrust
Rc::try_unwrap(handle) -> Result<T, Rc<T>>

Working Example

Example Snippetrust
use std::rc::Rc;fn main() {    let ticket = Rc::new(String::from("A12"));    let other = Rc::clone(&ticket);    let ticket = Rc::try_unwrap(ticket).unwrap_err();    drop(other);    println!("{}", Rc::try_unwrap(ticket).unwrap());}
Rust Reference