The Rc Smart Pointer In Rust

Table of contents

No heading

No headings in the article.

In Rust, the Rc (short for "reference counting") type is a smart pointer that allows you to share ownership of a value between multiple variables. It is defined in the std::rc module and is commonly used when you want to store a value in a data structure that may have multiple references to it, such as in a tree-like data structure.

Here is a basic example of using an Rc to share ownership of a value:

use std::rc::Rc;

fn main() {
    let a = Rc::new(5);
    let b = a.clone();
    let c = a.clone();

    println!("a = {}, b = {}, c = {}", a, b, c);
}

In this example, we create a new Rc containing the value 5 and then create two more variables, b and c, that share ownership of the value. When we call the clone method on an Rc value, it increases the reference count by one. This means that there are now three variables that share ownership of the value.

You can access the value stored in an Rc using the * operator, just like you would with a regular reference. Here is an example of using the * operator to access the value stored in an Rc:

use std::rc::Rc;

fn main() {
    let a = Rc::new(5);
    let b = a.clone();
    let c = a.clone();

    println!("a = {}, b = {}, c = {}", *a, *b, *c);
}

When all of the variables that share ownership of a value are dropped, the value will also be dropped. Here is an example of using an Rc in a tree-like data structure:

use std::rc::Rc;

struct Node {
    value: i32,
    children: Vec<Rc<Node>>,
}

fn main() {
    let a = Rc::new(Node { value: 5, children: vec![] });
    let b = Rc::new(Node { value: 6, children: vec![a.clone()] });
    let c = Rc::new(Node { value: 7, children: vec![a.clone(), b.clone()] });

    println!("a = {}, b = {}, c = {}", a.value, b.value, c.value);
}

In this example, we have a Node struct that contains a value and a vector of children nodes. We create three nodes, a, b, and c, and add them to each other's children vectors. We use Rc to share ownership of the nodes between the children vectors. When all of the variables that share ownership of a node are dropped, the node and all of its children will also be dropped.

One thing to note is that Rc is not thread-safe. If you want to share ownership of a value between threads, you should use the Arc type (short for "atomic reference counting") instead.

I hope this tutorial has helped you understand how to use the Rc smart pointer in Rust. If you have any questions or want to learn more, feel free to ask!

Did you find this article valuable?

Support Joshua Rosato by becoming a sponsor. Any amount is appreciated!