Rc<T> (Reference Counting) enables shared ownership of heap-allocated data in single-threaded contexts. Unlike Box<T> where ownership is unique, Rc<T> allows multiple parts of your code to own the same data. The strong_count() method returns how many Rc references point to the data. When the last Rc is dropped, the inner data is automatically deallocated. Rc<T> provides only shared (immutable) access; for mutable shared ownership, you would need RefCell<T> inside Rc<T>. This is useful for caches, configuration objects, or any data that needs to be accessed from multiple places without clear ownership.
use std::rc::Rc;#[derive(Debug)]struct Config {name: String,version: String,}fn main() {let config = Rc::new(Config {name: "MyApp".to_string(),version: "1.0.0".to_string(),});println!("Original ref count: {}", Rc::strong_count(&config));{let config_clone = Rc::clone(&config);println!("After clone ref count: {}", Rc::strong_count(&config_clone));println!("Config in scope: {:?}", config_clone);}println!("After scope ref count: {}", Rc::strong_count(&config));let another_clone = Rc::clone(&config);println!("Final ref count: {}", Rc::strong_count(&another_clone));drop(another_clone);println!("After drop ref count: {}", Rc::strong_count(&config));}