use std::rc::Rc; // A simple data structure that we want to share ownership of struct Gadget { id: u32, name: String, } impl Gadget { fn new(id: u32, name: &str) -> Self { Gadget { id, name: name.to_string() } } } fn main() { let gadget_original = Rc::new(Gadget::new(1, "SuperWidget")); println!("Initial RefCount for gadget_original: {}", Rc::strong_count(&gadget_original)); // Create a new scope to demonstrate how Rc works { let gadget_clone1 = Rc::clone(&gadget_original); // Increase ref count let gadget_clone2 = Rc::clone(&gadget_original); // Increase ref count again println!("Gadget 1 ID: {}, Name: {}", gadget_clone1.id, gadget_clone1.name); println!("Gadget 2 ID: {}, Name: {}", gadget_clone2.id, gadget_clone2.name); println!("RefCount inside scope: {}", Rc::strong_count(&gadget_original)); // When gadget_clone1 and gadget_clone2 go out of scope, their ref counts decrease. } // gadget_clone1 and gadget_clone2 are dropped here. println!("RefCount after scope: {}", Rc::strong_count(&gadget_original)); // When gadget_original goes out of scope, the Gadget data on the heap will be dropped // because its strong_count will become zero. // This demonstrates safe shared ownership without manual memory management. // Rc is for single-threaded scenarios. For multi-threaded shared ownership, use Arc. // Rc allows multiple immutable references to the same data. // If you need mutable shared data, combine Rc with RefCell. (See next snippet) }