Rc, short for reference counted, is a Rust smart pointer for shared ownership. It tracks how many owning references point to a value and drops that value when the count reaches zero. section 11.5 section 11.5.1
Rust normally gives each value one owner. Rc provides another option when copying an entire value would be expensive or impossible: cloning an Rc clones its pointer, not the data inside it. section 11.5.1 section 11.5.2
Use Rc when several structures or function calls need to own the same data.
- Import it with use std::rc::Rc; and create shared data with Rc::new(value). section 11.5.2
- Create another owner with Rc::clone(&item), which makes the sharing explicit and avoids cloning the contained value. section 11.5.2
- Inspect the number of owning references with Rc::strong_count(&item). section 11.5.2
- Choose weak references for links that could form a reference cycle; weak references do not keep the value from being dropped. section 11.5.2
Sharing a city history
Store a long city history in Rc<String>, then clone the Rc into both City and CityData. The original String is shared rather than duplicated, and strong_count reports three owners after the demonstrated clones. section 11.5.2
fn takes_a_string(_unused_string: String) {}
fn main() {
let user_name = String::from("User MacUserson");
takes_a_string(user_name);
takes_a_string(user_name);
}
Compare the moved-String failure with Rc-based sharing: passing Rc::clone(&user_name) lets the same data reach a function twice. section 11.5.1 section 11.5.2
Rc can also replace lifetime-heavy borrowed strings in nested structs. Using Rc<String> for a city name removes the repeated lifetime annotations required by City, Country, and World. section 11.5.3

