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?
The presence of
selfas the first parameter of an associated function has special meaning, and has special shorthand syntax:selfis short forself: Self&selfis short forself: &Self&mut selfis short forself: &mut SelfSo you can see that the
mutin&mut selfis part of its type;selfis a mutable reference.For completeness, you may also see a lone
mutbefore 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 asletvslet mut. i.e.mut data: &u64would mean theu64being referenced cannot be modified, but the variabledatacan be re-assigned to reference a differentu64.