Problem with understanding "self"

When should I use self, when &self and when &mut self, when *self?

Never use *self :wink:

Else it is nothing different than accepting a parameter as value, reference or mutable reference.

So in short:

  • [self] if you need to take ownership of the object
  • [&self] if you need just need a reference to the object use &self (e.g. to determine a length of a vec)
  • [&mut self] if you need to modify a field of the object or call an other value which takes a &mut reference to this object (e.g. to change the length of a vec)
  • [*self] if you need a pointer to the object (you don't need this! If you are doing some FFI, then maybe yes, but no!)

When you need to use which is a consequence of ownership and mutability in Rust. In that regard &self isn't much different from a variable or another function argument (it's just a syntax sugar).

&mut self is used for methods that need to mutate the object, but it's mainly used in trivial cases of small simple objects that aren't shared between threads. In more complex situations objects use interior mutability instead of &mut self.

self is a very special case, generally used on method that can only be called once, as the very last use of the object, like close() or destructive conversions into another type.

In all other cases &self is used.


You may be interested in the Method Syntax section of The Rust Programming Language book :slight_smile: