Shared Ownership for Single Threaded Data with Rc<T>
Owner: SnippetBot
Created: 2026-09-28 00:00:24
Size: 1.29 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
use std::rc::Rc;
// Define a simple enum for a linked list that can have multiple owners
enum List {
Cons(i32, Rc<List>),
Nil,
}
use List::{Cons, Nil};
fn main() {
let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil)))));
println!("Reference count after creating a = {}", Rc::strong_count(&a)); // 1
// b and c now share ownership of the data pointed to by 'a'.
// The reference count for the data increases.
let b = Cons(3, Rc::clone(&a));
println!("Reference count after creating b = {}", Rc::strong_count(&a)); // 2
{
let c = Cons(4, Rc::clone(&a));
println!("Reference count after creating c = {}", Rc::strong_count(&a)); // 3
// c goes out of scope here, reference count decreases
}
println!("Reference count after c goes out of scope = {}", Rc::strong_count(&a)); // 2
// When 'b' goes out of scope, the count will be 1.
// When 'a' goes out of scope, the count will be 0, and the memory will be deallocated.
// This allows multiple immutable owners of the same data.
// The Debug trait is not automatically implemented for `List` due to the recursive nature,
// so printing directly with `{:?}` might not work without a manual Debug impl.
// For demonstration, imagine inspecting the structure's shared state.
}