I was working through this exercise (mutable pass-by-mutable reference)and not able to comprehend the result
#[derive(Debug)]
struct Person {
name: String,
age: u32,
}
fn birthday_mutable<'a>(mut person: &'a mut Person, replacement: &'a mut Person) {
println!("[InFn] Before : Alice {:p} : {:?}, Bob {:p} : {:?}", &person, person, &replacement, replacement);
person = replacement;
println!("[InFn] After : Alice {:p} : {:?}", &person, person);
}
fn main() {
let mut alice = Person {
name: String::from("Alice"),
age: 30,
};
let mut bob = Person {
name: String::from("Bob"),
age: 20,
};
println!("[Main] Before : Alice {:p} : {:?}, Bob {:p} : {:?}", &alice, alice, &bob, bob);
birthday_mutable(&mut alice, &mut bob);
println!("[Main] After : Alice {:p} : {:?}, Bob {:p} : {:?}", &alice, alice, &bob, bob);
}
In the birthday_mutable function, person is in a mutable variable. The first thing we do is person = replacement;. This changes what our person variable is pointing at, and does not modify the original value being pointed at by the reference at all.
Despite for changing what person points to, yet the result is this
[Main] Before : Alice 0x7ffd0c9b77e0 : Person { name: "Alice", age: 30 }, Bob 0x7ffd0c9b7820 : Person { name: "Bob", age: 20 }
[InFn] Before : Alice 0x7ffd0c9b7568 : Person { name: "Alice", age: 30 }, Bob 0x7ffd0c9b7570 : Person { name: "Bob", age: 20 }
[InFn] After : Alice 0x7ffd0c9b7568 : Person { name: "Bob", age: 20 }
[Main] After : Alice 0x7ffd0c9b77e0 : Person { name: "Alice", age: 30 }, Bob 0x7ffd0c9b7820 : Person { name: "Bob", age: 20 }
Based on my understanding shouldn't the result be this?
[Main] Before : Alice 0x7ffd0c9b77e0 : Person { name: "Alice", age: 30 }, Bob 0x7ffd0c9b7820 : Person { name: "Bob", age: 20 }
[InFn] Before : Alice 0x7ffd0c9b7568 : Person { name: "Alice", age: 30 }, Bob 0x7ffd0c9b7570 : Person { name: "Bob", age: 20 }
[InFn] After : Alice 0x7ffd0c9b7568 : Person { name: "Bob", age: 20 }
[Main] After : Alice 0x7ffd0c9b77e0 : Person { name: "Bob", age: 20 } , Bob 0x7ffd0c9b7820 : Person { name: "Bob", age: 20 }
Can someone please explain why?
aliceare unchanged, so why would it print"Bob"in main?