Hey guys,
I guess this isn't possible in rust, but I'm curious whether it is possible to trigger an event when the value of a variable changes, or the field of a struct updates.
I thought about borrowing the reference, but then you actually aren't able to update it anymore,
Overloading the assignment of a variable is also not possible.
One use case:
Collecting updated data -> upload those changes automatically after some time.
The only way to do this is to make the fields private and force everyone to modify them through helper methods. Then you can call the listeners manually in the helper methods.
This wouldn’t detect every update but every deref. Users could hold onto a reference returned by the Deref(Mut) implementation for a potentially very long time and do lots of updates without triggering any extra code to be run.
Note that what you can do by using Deref is executing code at the start of the borrow. You won’t see when the mutating is finished, instead you only see once the next mutation starts. One way to indicate when one kind-of atomic “mutation operation” is finished is by offering some kind of guard object that will execute some code once it’s dropped. The guard object itself would then implement Deref and DerefMut in order to provide access to the thing that it’s guarding. I’m thinking somewhat similar in API to Mutex and RefCell in std.
If you are OK with not observing every individual memory write, but you are only interested in observing (potentially accumulated or batch) changes once a mutable borrower is done with your data, then a more principled approach would be to define an RAII guard, something like RefCell's RefMut or Mutex's MutexGuard, which DerefMut's to the inner data, and calls any necessary event handling logic in its destructor. Something like this (Playground):