Instead of DerefMut
, you could override operators like AddAssign
:
impl std::ops::AddAssign<i32> for Wallet {
fn add_assign(&mut self, x: i32) {
self.value += x;
possibly_updated(&self.name, &self.value);
}
}
tomWallet += 50;
But you probably want to support arbitrary operations, not just addition. In this case, you could use a closure-based API:
impl Wallet {
fn update(&mut self, f: impl FnOnce(&mut i32)) {
f(&mut self.value);
possibly_updated(&self.name, &self.value);
}
}
tomWallet.update(|value| {
*value += 50;
});
But if you give out a &mut i32
reference, there is no “hook” that lets you run arbitrary code when someone writes to it. And this can't be changed because unsafe code relies on it.