Last active
March 1, 2022 23:43
-
-
Save charlespierce/27bec09d15f303b99739775f3a2a19c6 to your computer and use it in GitHub Desktop.
Example of using Rc for shared ownership
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[derive(Debug)] | |
struct Pet { | |
name: String, | |
} | |
impl Pet { | |
fn new(name: String) -> Self { | |
Self { name } | |
} | |
} | |
struct Person { | |
pets: Vec<Rc<Pet>>, | |
} | |
fn main() { | |
// Create two pets with shared ownership | |
let cat = Rc::new(Pet::new("Tigger".into())); | |
let dog = Rc::new(Pet::new("Chase".into())); | |
// Create one person who owns both pets | |
let brother = Person { | |
pets: vec![cat.clone(), dog.clone()], | |
}; | |
// Create another person who _also_ owns both pets | |
let sister = Person { | |
pets: vec![cat, dog], | |
}; | |
// Even if one person gives up ownership, the other person still has shared ownership, | |
// so the pets are kept around (yay!) | |
drop(sister); | |
println!("Pets: {:?}", brother.pets) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment