Can't change value of attribute


#1

Why doesn’t the following (executable) code change the value of attribute ‘a’? (muting ‘c’ won’t help) Thanks.


pub struct T {
    pub a: i32,
}

impl T {

    fn change(&mut self, i: i32) {

        let c = &mut match i {
            1 => {
                println!("Changing...");
                self.a
            }
            _ => panic!("Try 1!"),

        };
        *c = i;
      }
}


fn main() {
    let mut t = T { a: 0 };
    println!("Old value: {}", t.a);
    t.change(1);
    println!("New value: {}", t.a);
}

#2

The value of self.a is copied (because i32 implements Copy) to a temporary variable on the stack and then c is assigned a reference to that anonymous variable. For c to reference the a field the match needs to return that reference:

    let c = match i {
        1 => {
            println!("Changing...");
            &mut self.a
        }
        _ => panic!("Try 1!"),
    };

#3

Wow that’s tricky; indeed, understanding Rust forces one to learn thinking as a compiler… Thanks!


#4

Curiously: How do you “colorize” your Rust code? (I’m using the html “pre” tags…).


#5
```rust
code goes here
```

#6

:slight_smile:!