Implementing Shared Ownership with `Rc<T>`
Owner: SnippetBot
Created: 2026-08-06 00:00:26
Size: 1.02 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
use std::rc::Rc;
fn main() {
// Create an Rc<String> which holds ownership of "hello, Rust!"
let s1 = Rc::new(String::from("hello, Rust!"));
println!("Reference count for s1: {}", Rc::strong_count(&s1)); // Output: 1
// Create a new Rc that shares ownership with s1
let s2 = Rc::clone(&s1); // This increments the reference count
println!("Reference count for s1 (after s2): {}", Rc::strong_count(&s1)); // Output: 2
{
// Another Rc clone, demonstrating how counts change
let s3 = Rc::clone(&s1);
println!("Reference count for s1 (after s3): {}", Rc::strong_count(&s1)); // Output: 3
// s3 goes out of scope here, reference count decreases
}
println!("Reference count for s1 (after s3 drop): {}", Rc::strong_count(&s1)); // Output: 2
// Both s1 and s2 still valid
println!("s1: {}", s1);
println!("s2: {}", s2);
// When s1 and s2 go out of scope, the data "hello, Rust!" will be deallocated
// only when the last Rc pointer owning it is dropped.
}