Rc<T> (Rust)

Rc<T> is a reference-counted smart pointer for shared ownership in a single thread. Multiple Rc handles can own the same value; the data is dropped when the last one goes away.

Rust

Sometimes a value needs more than one owner — a node referenced by several parts of a graph, for example. Rc<T> ('reference counted') tracks how many handles exist. Calling Rc::clone bumps the count (it does not deep-copy the data); when the count hits zero the value is freed.

Rc only gives shared, immutable access and is not thread-safe — its counter isn't atomic. For shared ownership across threads use Arc instead. To mutate data behind an Rc, combine it with RefCell as Rc<RefCell<T>>.

Rc::clone is cheap and conventional (over .clone()) to signal you're copying a pointer, not the data. Watch out for reference cycles, which leak memory; break them with Weak references.

Syntax

use std::rc::Rc;
let a = Rc::new(5);
let b = Rc::clone(&a); // shared ownership

Examples

Rust

use std::rc::Rc;

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

Output:

shared shared
count=2

Learn it in a lesson

See also

Back to the Dictionary