Function call when derefmut value is assigned

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;

(Playground)

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;
});

(Playground)

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.

2 Likes