rusttypesreferencemutable-reference

Why are mutable references inconsistent between impl and normal functions?


For functions in an impl block we use this syntax:

fn test(&mut self) {}

But for a normal function we use this syntax:

fn test(data: &mut u64) {}

I understand self is a variable, while Self is type. In first case we use &mut with the variable (self), but in the second then we used &mut with the type (u64). Why is there this inconsistency?


Solution

  • The presence of self as the first parameter of an associated function has special meaning, and has special shorthand syntax:

    So you can see that the mut in &mut self is part of its type; self is a mutable reference.


    For completeness, you may also see a lone mut before the parameter name and type. This would mean the variable can be mutated and rebound, but does not affect the type. This is the same distinction as let vs let mut. i.e. mut data: &u64 would mean the u64 being referenced cannot be modified, but the variable data can be re-assigned to reference a different u64.