Weak References
Weak<T> is a non-owning reference to Rc/Arc data - breaks cycles via upgrade() to Option<Rc/Arc>.
Busca en todas las páginas de la documentación
Weak<T> is a non-owning reference to Rc/Arc data - breaks cycles via upgrade() to Option<Rc/Arc>.
use std::rc::{Rc, Weak};
struct Node { value: i32, parent: Option<Weak<Node>>, child: Option<Rc<Node>> }When to reach for this: Parent pointers in trees/graphs without leaking Rc cycles.
use std::rc::{Rc, Weak};
struct Owner { name: String }
struct Observer { owner: Weak<Owner> }
fn main() {
let owner = Rc::new(Owner { name: "app".into() });
let obs = Observer { owner: Rc::downgrade(&owner) };
if let Some(o) = obs.owner.upgrade() {
println!("{}", o.name);
}
}What this demonstrates:
downgrade from Rc to Weakupgrade returns None if owner droppedCycles: A Rc-> B Rc-> A leak memory. Make one direction Weak. Arc::downgrade same for threads.
None means gone. Fix: Handle absent owner.Rc from upgrade promptly if not needed.Arc.Arc.| Alternative | Use When | Don't Use When |
|---|---|---|
| Indices into arena | No refcount | Need Rc ergonomics |
| Owned graph | Clear tree ownership | Back pointers needed |
| Channels events | Decouple lifetimes | Direct observation |
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Revisado por Chris St. John·Última actualización: 16 jul 2026