0
0
Rustprogramming~5 mins

Rc pointer in Rust

Choose your learning style9 modes available
Introduction

An Rc pointer lets multiple parts of your program share ownership of some data. It keeps track of how many owners there are and cleans up the data when no one uses it anymore.

When you want to share read-only data between different parts of your program without copying it.
When you have multiple owners of the same data and you don't know which one will finish using it last.
When you want to avoid complex lifetime management by letting Rust count owners for you.
When you build tree-like or graph-like structures where nodes share ownership of other nodes.
Syntax
Rust
use std::rc::Rc;

let shared_value = Rc::new(5);

Rc::new(value) creates a new reference-counted pointer to value.

You can clone an Rc to increase the count and share ownership.

Examples
Here, b shares ownership of the value 10 with a. Both point to the same data.
Rust
use std::rc::Rc;

let a = Rc::new(10);
let b = Rc::clone(&a);
This prints how many owners currently share the data.
Rust
use std::rc::Rc;

let data = Rc::new(String::from("hello"));
println!("Count: {}", Rc::strong_count(&data));
Sample Program

This program shows how the reference count changes as we clone and drop Rc pointers. It prints the count before cloning, after cloning, inside a block with another clone, and after the block ends.

Rust
use std::rc::Rc;

fn main() {
    let shared = Rc::new(String::from("Rust"));
    println!("Initial count: {}", Rc::strong_count(&shared));

    let shared_clone = Rc::clone(&shared);
    println!("Count after clone: {}", Rc::strong_count(&shared));

    {
        let another_clone = Rc::clone(&shared);
        println!("Count inside block: {}", Rc::strong_count(&shared));
    }

    println!("Count after block: {}", Rc::strong_count(&shared));
    println!("Value: {}", shared);
}
OutputSuccess
Important Notes

Rc only works in single-threaded scenarios. For multi-threaded sharing, use Arc.

Cloning an Rc is cheap because it only increases the count, it does not copy the data.

Be careful to avoid reference cycles with Rc, as they cause memory leaks.

Summary

Rc lets multiple owners share read-only data safely in one thread.

Use Rc::clone(&value) to add owners and increase the count.

The data is cleaned up automatically when the last owner goes away.