|
| 1 | +# `Rc` |
| 2 | + |
| 3 | +When multiple ownership is needed, `Rc`(Reference Counting) can be used. `Rc` keeps track of the number of the references which means the number of owners of the value wrapped inside an `Rc`. |
| 4 | + |
| 5 | +Reference count of an `Rc` increases by 1 whenever an `Rc` is cloned, and decreases by 1 whenever one cloned `Rc` is dropped out of the scope. When an `Rc`'s reference count becomes zero, which means there are no owners remained, both the `Rc` and the value are all dropped. |
| 6 | + |
| 7 | +Cloning an `Rc` never do a deep copy. Cloning creates just another pointer to the wrapped value, and increments the count. |
| 8 | + |
| 9 | +```rust,editable |
| 10 | +use std::rc::Rc; |
| 11 | +
|
| 12 | +fn main() { |
| 13 | + let rc_examples = "Rc examples".to_string(); |
| 14 | + { |
| 15 | + println!("--- rc_a is created ---"); |
| 16 | + |
| 17 | + let rc_a: Rc<String> = Rc::new(rc_examples); |
| 18 | + println!("Reference Count of rc_a: {}", Rc::strong_count(&rc_a)); |
| 19 | + |
| 20 | + { |
| 21 | + println!("--- rc_a is cloned to rc_b ---"); |
| 22 | + |
| 23 | + let rc_b: Rc<String> = Rc::clone(&rc_a); |
| 24 | + println!("Reference Count of rc_b: {}", Rc::strong_count(&rc_b)); |
| 25 | + println!("Reference Count of rc_a: {}", Rc::strong_count(&rc_a)); |
| 26 | + |
| 27 | + // Two `Rc`s are equal if their inner values are equal |
| 28 | + println!("rc_a and rc_b are equal: {}", rc_a.eq(&rc_b)); |
| 29 | + |
| 30 | + // We can use methods of a value directly |
| 31 | + println!("Length of the value inside rc_a: {}", rc_a.len()); |
| 32 | + println!("Value of rc_b: {}", rc_b); |
| 33 | + |
| 34 | + println!("--- rc_b is dropped out of scope ---"); |
| 35 | + } |
| 36 | + |
| 37 | + println!("Reference Count of rc_a: {}", Rc::strong_count(&rc_a)); |
| 38 | + |
| 39 | + println!("--- rc_a is dropped out of scope ---"); |
| 40 | + } |
| 41 | + |
| 42 | + // Error! `rc_examples` already moved into `rc_a` |
| 43 | + // And when `rc_a` is dropped, `rc_examples` is dropped together |
| 44 | + // println!("rc_examples: {}", rc_examples); |
| 45 | + // TODO ^ Try uncommenting this line |
| 46 | +} |
| 47 | +``` |
| 48 | + |
| 49 | +### See also |
| 50 | + |
| 51 | +[std::rc][1] and [Arc][2]. |
| 52 | + |
| 53 | +[1]: https://doc.rust-lang.org/std/rc/index.html |
| 54 | +[2]: https://doc.rust-lang.org/std/sync/struct.Arc.html |
0 commit comments