std-method

Rust Weak::upgrade

Convert a weak observer to an owning handle only if the payload is still available. Holding the returned Some handle keeps the payload alive. The same pattern works with sync::Weak returning Arc instead. Expected output (not executed): open true Why: The successful upgrade creates a new strong owner until held is dropped. Common mistake: Unwrapping a weak pointer in a long-lived cache where the target may disappear.

Formal Syntax & Structure

rust syntaxrust
observer.upgrade() -> Option<Rc<T>>

Working Example

Example Snippetrust
use std::rc::Rc;fn main() {    let session = Rc::new(String::from("open"));    let observer = Rc::downgrade(&session);    let held = observer.upgrade().unwrap();    drop(session);    println!("{held}");    drop(held);    println!("{}", observer.upgrade().is_none());}
Rust Reference