Reference counting
Sometimes you need several references to an immutable value at the same time, this is also called shared ownership. The pointer type Box<T>
can't help us out here, because this type has a single owner by definition. For this, Rust provides the generic reference counted box Rc<T>
, where multiple references can share the same resource. The std::rc
module provides a way to share ownership of the same value between different Rc
pointers; the value remains alive as long as there is least one pointer referencing it.
In the following example, we have Aliens that have a number of tentacles. Each Tentacle
is also a struct instance and has to indicate to which Alien
it belongs; besides that it has other properties like a degree of poison. A first attempt at this could be the following code which however does not compile:
// see Chapter 7/code/refcount_not_good.rs): struct Alien { name: String, n_tentacles: u8 } struct Tentacle { poison: u8, owner...