Introduction
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 which determines whether or not a
value is still in use. If there are zero references to a value, the
value can be cleaned up without any references becoming invalid.
Reason to choose Rc<T>
Rc<T>
enables multiple owners of the same data;
Box<T> and
RefCell<T> have single owners.
Example
This won’t compile because b & c both share ownership of a:
The solution: