Rc<T>
, the Reference Counted Smart Pointer
In the majority of cases, ownership is clear: you know exactly which variable owns a given value. However, there are cases when a single value might have multiple owners. For example, in graph data structures, multiple edges might point to the same node, and that node is conceptually owned by all of the edges that point to it. A node shouldn’t be cleaned up unless it doesn’t have any edges pointing to it.
To enable multiple ownership, Rust has a type called Rc<T>
, which is an abbreviation for reference counting. The Rc<T>
type keeps track of the number of references to a value to determine whether or not the value is still in use. If there are zero references to a value, the value can be cleaned up without any references becoming invalid.
Note that Rc<T>
is only for use in single-threaded scenarios.
Using Rc<T>
to Share Data
Each Cons
variant will now hold a value and an Rc<T>
pointing to a List
.
When we create b
, instead of taking ownership of a
, we’ll clone the Rc<List>
that a
is holding, thereby increasing the number of references from one to two and letting a
and b
share ownership of the data in that Rc<List>
.
use std::rc::Rc; pub enum List { Cons(i32, Rc<List>), Nil, } use crate::base::l1_rc::List::{Cons, Nil}; pub fn test() { let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); let b = Cons(3, Rc::clone(&a)); let c = Cons(4, Rc::clone(&a)); }
We’ll also clone a
when creating c
, increasing the number of references from two to three.
Every time we call Rc::clone
, the reference count to the data within the Rc<List>
will increase, and the data won’t be cleaned up unless there are zero references to it.
We could have called a.clone()
rather than Rc::clone(&a)
, but Rust’s convention is to use Rc::clone
in this case. The implementation of Rc::clone
doesn’t make a deep copy of all the data like most types’ implementations of clone
do. The call to Rc::clone
only increments the reference count, which doesn’t take much time. Deep copies of data can take a lot of time.