Why is `mut self` a thing? (and mutable moves in general)

63 points wldmr

Trying to get to grips with Rust and I can't quite wrap my head around why there is both self and mut self. Consider:

fn fn_mut_mov(mut self) -> Self {
    self.value += 1;
    self
}

fn fn_mov(self) -> Self {
    let mut result = self;
    result.value += 1;
    result
}

From where I'm standing, these two functions are completely indistinguishable from the caller's perspective, right?

The obvious answer is of course “mut self shows the intent better”, which I'm not wholly convinced by. The caller can't ever observe that mutation (right?), so why would I want to announce anything about my intent? self is mine now, never you mind what I do with it. I would even expect (having done no research whatsoever …) that those two functions compile down to the same machine code.

A couple of notes:

  • For context: I'm working through Algebra Driven Design, where immutability reigns supreme. Therefore, the signature of fn_mov seemed much more natural to me, and I was a bit surprised by that extra bit of let result ceremony I had to do to achieve it.

  • To be clear: I'm not trying to litigate the language design. Rather, I'm trying to find out if there's a practical difference between mutable and immutable moves that goes beyond communicating intent.

  • I did a bit a searching on the topic, but searching for "rust mutable move" seems to exclusively talk about either mutable references or move closures. If there is a more salient keyword to look for, that'd be great too.

Edit: OK, so mut isn't actually part of the function signature, and “mutable moves” aren't actually a thing. Now don't I feel silly for asking such a basic question. This really should have gone into /r/learnrust or the questions thread. Sorry for the noise.