Course contentsShow
← Rust
Lesson 38 of 1,9101. Rust Fundamentals and ToolingFree lesson

Reference Counting for Shared Ownership

Manage data with multiple owners safely using reference counting pointers.

In this lesson, you will learn how to allow multiple parts of your code to own the same piece of data using the Rc<T> smart pointer.

The Limitation of Single Ownership

Up to this point, you have learned that Rust’s ownership rules strictly enforce that a value has one owner at a time. If you move a value into a function, the original scope loses access. While this is great for memory safety, it becomes difficult when you have data (like a configuration object or a shared graph node) that needs to be accessed by several different parts of your program simultaneously.

Enter Reference Counting

When you need multiple owners, you can use the Rc<T> type, which stands for Reference Counted.

Think of Rc<T> like a shared document in the cloud. Every time someone "opens" the document, the reference count increases. Every time someone "closes" it, the count decreases. As long as at least one person has the document open (the count is greater than zero), the data stays in memory. Once the last owner lets go, Rust automatically cleans up the memory.

How it works

To use Rc, you wrap your data inside it. When you want another owner, you call .clone() on the Rc pointer. Importantly, this does not create a deep copy of the underlying data; it only creates a new pointer to the same memory and increments the reference count.

use std::rc::Rc;

fn main() {
    // Create an Rc pointing to a string
    let shared_data = Rc::new(String::from("Shared Data"));
    
    // Increment the reference count by cloning the pointer
    let owner2 = Rc::clone(&shared_data);
    
    println!("Count: {}", Rc::strong_count(&shared_data)); // Prints 2
}

Because Rc<T> is immutable by default, it is perfect for shared data that needs to be read from many places but not changed. It allows you to bypass the single-owner restriction while ensuring the data is only destroyed when it is truly no longer needed.

Key Takeaway: Rc<T> enables shared ownership by keeping a running count of references to a heap-allocated value, ensuring the memory is only freed when the final owner drops the reference.