typestar

Rc shared ownership in Rust

Reference counting for multiple owners of one value.

use std::rc::Rc;

fn main() {
    let shared = Rc::new(vec![1, 2, 3]);
    let a = Rc::clone(&shared);
    let b = Rc::clone(&shared);

    let count = Rc::strong_count(&shared);
    let total: i32 = a.iter().sum();
    println!("{count} {total} {}", b.len());
}

How it works

  1. Rc::new wraps a value for sharing.
  2. Rc::clone bumps the count, not the data.
  3. strong_count reports how many owners exist.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
238
Tokens
91
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 55 seconds.

Type this snippet

Step 2 of 2 in Smart pointers, step 14 of 15 in Ownership & borrowing.

← Previous Next →