liveBook · Manning

Rc

As explained in Learn Rust in a Month of Lunches

Rc is Rust's reference-counting smart pointer type for shared ownership of data while tracking the number of active owning references.

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

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains construction, cloning, owner counts, weak references, cycles, and lifetime avoidance through worked examples.
Examples
Uses moved Strings, shared city names and histories, repeated function calls, owner counts, and nested city-country-world structs.
What it assumes
Assumes basic ownership and borrowing, then addresses moved values, shared ownership, and lifetime annotations through compiler feedback.
What you can do after
Apply it via std::rc::Rc to share data, inspect strong counts, and replace selected lifetime-heavy string references.
How it connects
Connects shared ownership with ownership, cloning, lifetimes, weak references, reference cycles, and garbage collection.

Also explained in

Compare how 2 books explain Rc →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.