RRust By Example

Rc<T> Reference Counting

Share ownership with reference counting.

Rc<T> Reference Counting

Share ownership with reference counting.

Difficulty

Advanced

Code

rust
use std::rc::Rc;

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

    println!("a: {:?}", a);
    println!("b: {:?}", b);
    println!("reference count: {}", Rc::strong_count(&a));
}

Explanation

Rc enables shared ownership with reference counting.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the smart-pointers category to build a complete understanding of this topic.

More Smart Pointers Examples