Method types based on borrowing

The borrowing rules also dictate how inherent methods on types are defined and also instance methods from traits. The following are how they receive the instance, presented by least restrictive to most restrictive:

  • &self methods: These methods only have immutable access to its members
  • &mut self methods: These methods borrows the self instance mutably
  • self methods: These methods takes ownership of the instance on which it is called and the type is not available to be called later

In the case of user defined types, the same kind of borrowing applies also to its field members.

Note: Unless you're deliberately writing a method that should move or drop self at the end, always prefer immutable borrowing methods that is, having &self as the first parameter.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset