Why do we need them?

Rust's ownership model normally allows only one owner for a value.

let s = String::from("Hello");

let a = s;
let b = s; // ERRORRRRRRR

Sometimes, however, multiple parts of a program should share ownership of the same data. And that's what reference counting solves.


Rc<T> (Reference Counted)

Rc<T> allows multiple owners of the same value within a single thread

use std::rc::Rc;
let message = Rc::new(String::from("Hello"));

let a = Rc::clone(&message);
let b = Rc::clone(&message);

And now all three variables own the same allocation

image.png

There's still only one String in memory


How does it work?

Internally: Rc stores a reference counter.

Initially:Reference count = 1After Cloning:Reference Count = 2After another clone:Reference count = 3

So whenever one owner is dropped:Reference count -= 1

Only when the counter reaches 0 is the underlying value freed.

Reference count = 0
        ↓
Memory is released

Notice this: Rc::clone() does not clone the data, it only creates another owner by increasing the reference count

Why can't Rc be used with threads?