0

Some operations have traits that can effectively be used to respond when operations are called, like below:

use std::ops;

#[derive(Debug)]
struct MyNum(u32);

impl ops::Add for MyNum {
    type Output = Self;

    fn add(self, b: Self) -> Self {
        println!("Added {} and {}", self.0, b.0);
        MyNum(self.0 + b.0)
    }
}

fn main() {
    let a = MyNum(1);
    let b = MyNum(2);
    let c = a + b;
    println!("C = {}", c.0);
}

However, as the docs state:

since the assignment operator (=) has no backing trait, there is no way of overloading its semantics

I want to be able to listen to when values are mutated via the assignment operator. The idea being to develop something similar to the Svelte library but in Rust. What would be the best approach to capture where variables are mutated - ideally keeping any overhead in the compile stage?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
APL
  • 1
  • I hope somebody will correct me, but Rust has affine types system, which means that each object might be used at most once, so every assignment from language's perspective is creation of a new object. So it's not like an object is mutated from an assignment. It's entirely another object – Alexey S. Larionov Aug 17 '20 at 18:26
  • As the docs you linked to state, you can't. Additionally, handling just the assignment operator doesn't capture all the possible types of mutation (e.g. `a += 1` doesn't use assignment operator, nor does `String::clear`). – Shepmaster Aug 17 '20 at 18:26
  • 1
    One thing I'd encourage you to do is to step up the abstraction hierarchy a bit and figure out why you want to do this. In many languages, you want to avoid mutability for *a specific reason*, not just because you can. It's frequently the case that you can accomplish that real reason via a different mechanism. Said another way, find an idiomatic tool to suit the problem, not just a tool that looks the same as the tool you are used to. – Shepmaster Aug 17 '20 at 18:29
  • thanks for your comments. The driving force for this is to create a reactive system, where we can define how values are derived and allow them to be updated automatically, for example consider the example: ` let a = 2; let b = 3; let c = a + b; ` If a or b are ever changed I want c to be updated automatically. I could use a closure for c instead and call it when I want to fetch the value and then opt for using a memorize func to save recalculating if a or b are unchanged. However I am looking to minimize the cost by moving the change logic to the compiler stage, like Svelte. – APL Aug 17 '20 at 18:49

0 Answers0