Consider the following code:
struct Person {
name: String,
}
impl Person {
fn mutate_me(&mut self) {
// immutable instances fail to be mutated here:
self.name.push_str("ABCD");
println!("{}", self.name);
}
}
impl Drop for Person {
fn drop(&mut self) {
// immutable instances are successfully mutated here:
self.name.push_str("EFGH");
println!("{}", self.name);
}
}
fn main() {
// this instance is not mutable:
let person = Person {
name: "John".to_owned(),
};
// the following line expectedly fails:
// person.mutate_me();
} // the call to the drop function (which mutates) is successful here
The mutate_me()
call fails as person
wasn't declared as mut
. The drop function, however, is successfully called right before the instance goes out of scope, and successfully mutates the instance. I expect that implementing Drop
would need a mutable reference in many (most?) cases. But why can it receive a mutable reference when the instance isn't marked as mut
?