Created
February 11, 2019 18:48
-
-
Save wdevore/381e81525f31a714efe1a8c031afb890 to your computer and use it in GitHub Desktop.
An example of passing a mutable borrow that is mutable parameter
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
// https://www.snoyman.com/blog/2018/11/rust-crash-course-05-rule-of-three | |
#[derive(Debug)] | |
struct Person { | |
name: String, | |
age: u32, | |
} | |
fn birthday_immutable(person: &mut Person) { | |
person.age += 1; | |
} | |
fn birthday_mutable<'a>(mut person: &'a mut Person, replacement: &'a mut Person) { | |
person = replacement; | |
person.age += 1; | |
} | |
fn main() { | |
let mut alice = Person { name: String::from("Alice"), age: 30 }; | |
let mut bob = Person { name: String::from("Bob"), age: 20 }; | |
println!("Alice 1: {:?}, Bob 1: {:?}", alice, bob); | |
birthday_immutable(&mut alice); | |
println!("Alice 2: {:?}, Bob 2: {:?}", alice, bob); | |
birthday_mutable(&mut alice, &mut bob); | |
println!("Alice 3: {:?}, Bob 3: {:?}", alice, bob); | |
} | |
// does not compile | |
fn birthday_immutable_broken<'a>(person: &'a mut Person, replacement: &'a mut Person) { | |
person = replacement; | |
person.age += 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment