Menu Close

Articles

Rust: Methods

Methods are functions bound to structured data types that can be called using dot notation. A method receive automatically first parameter that is called “self” representing a reference to current data object. This is how Rust enable object oriented programming.

Implementation

You can use keyword impl to create methods related to user define struct. This is the way to create object like structures in Rust. So rust has a kind of object oriented behavior but different than C++ or Java. Rust do not have class

Example:

Notes: 
  • Without impl , data structure has only basic methods,
  • Using impl you can declare more than one method,
  • Reference to self parameter is using symbol & as prefix,
  • Call for object method is using “.” after object name,
  • You must use () even if there are no parameters to make a valid call.

Homework: Open and run the example online: rust-method