Rc and shared ownership
Quick answer
Rc<T> lets several owners share a value on one thread. It counts strong owners and drops the value when the last strong owner disappears.
Clone the pointer, not the data
Rc::clone(&value) creates another owner of the same allocation. Rc::strong_count observes the count. Shared ownership normally gives shared access, not mutable access. Rc uses non-atomic counting and cannot be sent between threads.
use std::rc::Rc;fn main() { let a = Rc::new(String::from("book")); let b = Rc::clone(&a); println!("{}: {}", b, Rc::strong_count(&a)); drop(b); println!("{}", Rc::strong_count(&a)); }Expected stdout (not executed):
book: 21Dropping one owner does not drop the value while another owner remains.
use std::rc::Rc;fn main() { let mut a = Rc::new(4); *Rc::get_mut(&mut a).unwrap() = 7; let _b = Rc::clone(&a); println!("unique: {}, value: {}", Rc::get_mut(&mut a).is_some(), a); }Expected stdout (not executed):
unique: false, value: 7get_mut requires uniqueness, including absence of weak pointers.
Common mistake
Rc::clone does not clone the contained String or provide unrestricted mutation.
Try it yourself
Create three owners, drop one, and explain the remaining strong count.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Rc and shared ownership — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
Two Rc handles point to a String. Can Rc::get_mut give exclusive access while both exist?
Rc and shared ownership — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::rc::Rc; fn main() { let a = Rc::new(String::from("book")); let b = Rc::clone(&a); println!("{}: {}", b, Rc::strong_count(&a)); drop(b); println!("{}", Rc::strong_count(&a)); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Rc and shared ownership — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::rc::Rc; fn main() { let mut a = Rc::new(4); *Rc::get_mut(&mut a).unwrap() = 7; let _b = Rc::clone(&a); println!("unique: {}, value: {}", Rc::get_mut(&mut a).is_some(), a); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.