Rust shared ownership — Rc, Arc, and weak references

Contents

  1. 1. One owner
  2. 2. Deep copy (clone)
  3. 3. Reference counting (Rc)
  4. 4. Copy-on-write
  5. 5. Reference cycles
  6. 6. Weak references
  7. 7. Thread safety

One owner

Rust’s ownership model says each value has one owner. When the owner goes out of scope, the value is dropped.

In the snippet below, if a is moved into b, you cannot print a afterward — ownership already moved.

1
2
3
4
5
6
7
8
9
10
11
12
let a = String::from("hello");
let b = a;
println!("a = {}, b = {}", a, b);

// got error:
// error[E0382]: borrow of moved value: `a`
// 3 | let a = String::from("hello");
// | - move occurs because `a` has type `String`, which does not implement the `Copy` trait
// 4 | let b = a;
// | - value moved here
// 5 | println!("a = {}, b = {}", a, b);
// | ^ value borrowed here after move

Deep copy (clone)

clone gives you a second allocation. It works, but it is not cheap.

1
2
3
4
5
let a = String::from("hello");
// let b = a;
let b = a.clone();
println!("a = {}, b = {}", a, b);
// output: a = hello, b = hello

Reference counting (Rc)

Multiple owners without copying the payload each time — use reference counting via Rc.

Each clone bumps the count. When it hits zero, drop runs and memory is freed.

1
2
3
4
5
6
7
8
let a = Rc::new(String::from("hello"));
let _b = Rc::clone(&a);
{
let _b = Rc::clone(&a);
println!("reference count {}", Rc::strong_count(&a));
// 3, will be 2 after this block out of scope
}
println!("reference count {}", Rc::strong_count(&a)); // 2

Copy-on-write

The data inside an Rc is immutable through shared handles. To mutate in place, Rc::make_mut checks the strong count: if other live references exist, it clones the inner value and edits the clone; otherwise it mutates in place. That is copy-on-write — pay for a copy only when you need to diverge.

1
2
3
4
5
6
7
8
9
10
let mut a = Rc::new(String::from("hello"));
let b = Rc::clone(&a);
// allocate a new string (copy on write)
(*Rc::make_mut(&mut a)).push_str( " world");
println!("{} {}", a, b);
// hello world hello

let c = Rc::clone(&a);
println!("{} {} {}", a, b, c);
// hello world hello hello world

Edits stay isolated from older clones. If you want mutations visible through every handle, pair Rc with Cell or RefCell for interior mutability.

Reference cycles

Cycles break naive reference counting: counts never reach zero, so memory leaks.

The official gadget/owner example: tools point at an owner; the owner holds gadgets. With strong Rc links both ways, neither side can drop the other.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
use std::{rc::Rc, cell::RefCell};

struct Owner {
name: String,
gadgets: RefCell<Vec<Rc<Gadget>>>
}

struct Gadget {
id: i32,
owner: Rc<Owner>
}

fn main() {
let gadget_owner : Rc<Owner> = Rc::new(
Owner { name: String::from("Gadget Man"), gadgets: RefCell::new(vec![]) }
);
// two gadgets, same owner
let gadget1 = Rc::new(Gadget { id: 1, owner: gadget_owner.clone() });
let gadget2 =Rc::new(Gadget { id: 2, owner: gadget_owner.clone() });

gadget_owner.gadgets.borrow_mut().push(gadget1.clone());
gadget_owner.gadgets.borrow_mut().push(gadget2.clone());
// drop the owner's handle; gadgets still hold the owner
drop(gadget_owner);

println!("strong count of gadget1: {}", Rc::strong_count(&gadget1));
// strong count of gadget1: 2

println!("strong count of gadget1.owner: {}", Rc::strong_count(&gadget1.owner));
// strong count of gadget1.owner: 2

// drop gadget1 — without a cycle, the owner would go away too
// here gadget1.owner's count never drops, so the owner leaks
drop(gadget1);

println!("strong count of gadget2.owner: {}", Rc::strong_count(&gadget2.owner));
// strong count of gadget2.owner: 2
}

The cycle in plain terms:

1
2
3
4
5
6
7
8
9
gadgets and owner reference each other in a ring; neither side can release the other, counts never hit 0

+-----------+ +-----------+
| Owner |<------| Gadget |
| | | |
| Rc | | Rc |
| | | |
| gadgets --|------>| owner ----+
+-----------+ +-----------+

Weak references

Weak does not increment the strong count, so it cannot keep a cycle alive by itself.

A weak pointer may dangle once strong count hits zero. Call upgrade() for an Option<Rc<T>>.

Lifetime still follows strong references only.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
use std::rc::Rc;
use std::rc::Weak;
use std::cell::RefCell;

struct Owner {
name: String,
gadgets: RefCell<Vec<Weak<Gadget>>>
}

struct Gadget {
id: i32,
owner: Rc<Owner>
}

fn main() {
let gadget_owner : Rc<Owner> = Rc::new(
Owner {
name: "Gadget Man".to_string(),
gadgets: RefCell::new(Vec::new())
}
);

let gadget1 = Rc::new(Gadget{id: 1, owner: gadget_owner.clone()});
let gadget2 = Rc::new(Gadget{id: 2, owner: gadget_owner.clone()});

gadget_owner.gadgets.borrow_mut().push(Rc::downgrade(&gadget1.clone()));
gadget_owner.gadgets.borrow_mut().push(Rc::downgrade(&gadget2.clone()));

for gadget_opt in gadget_owner.gadgets.borrow().iter() {
let gadget = gadget_opt.upgrade().unwrap();
println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
}
drop(gadget_owner);
println!("strong count of gadget1: {}", Rc::strong_count(&gadget1));
// strong count of gadget1: 1
println!("strong count of gadget1.owner: {}", Rc::strong_count(&gadget1.owner));
// strong count of gadget1.owner: 2
drop(gadget1);

println!("strong count of gadget2.owner: {}", Rc::strong_count(&gadget2.owner));
// strong count of gadget2.owner: 1
}

Thread safety

Rc is not thread-safe. For sharing across threads, use Arc (atomic reference counting).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
use std::sync::Arc;
use std::thread;

fn main() {
let val = Arc::new(5);

for _ in 0..3 {
let val = Arc::clone(&val);
thread::spawn(move || {
let v = *val.as_ref() + 1;
println!("{v:?}");
});
}
thread::sleep(std::time::Duration::from_secs(1));
}

To mutate shared data on multiple threads, wrap the inner type in Mutex or RwLock, e.g. Arc<Mutex<T>>.


One more detail: both Rc<T> and Arc<T> deref to T, so you can call T methods on the smart pointer. To avoid ambiguity with T’s own methods, people often call smart-pointer methods with full qualification, e.g. Rc::clone.

Questions? Leave a comment below or email: newbvirgil@gmail.com