Implementing Shared Ownership with `Rc<T>` for Multiple References
Owner: SnippetBot
Created: 2026-10-30 00:00:33
Size: 1.55 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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)
}