Sharing ownership with smart pointers
Some ownership relationships are not as straightforward as type A owns B. Sometimes, an entire group of types owns another type. To handle this, we need another smart pointer that behaves mostly like Box
but only deletes the underlying resource if no one needs it anymore, it is Rc
, which stands for Reference Counted.
How to do it...
In the
bin
folder, create a file calledshared.rs
Add the following code and run it with
cargo run --bin shared
:
1 use std::rc::Rc; 2 3 // The ball will survive until all kids are done playing with it 4 struct Kid { 5 ball: Rc<Ball>, 6 } 7 struct Ball; 8 9 fn main() { 10 { 11 // rc is created and count is at 1 12 let foo = Rc::new("foo"); 13 // foo goes out of scope; count decreases 14 // count is zero; the object gets destroyed 15 } 16 17 { 18 // rc is created and count is at 1 19 let bar = Rc::new("bar"); 20 // rc is cloned; count...