Methods of Structs
Methods of Structs
- What Are Methods?
Methods are just like user-defined functions. They are like functions, but the only difference lies in the fact that methods are declared specifically within the struct context.
- Declare a Method
The method is like a regular function except that the &self parameter is passed to it and the items within the function are accessed through it.
Here self is the calling instance, i.e., it is referencing to the struct.
- Call a Method
An instance of the struct has to be created to invoke it. This is similar to invoking a struct.
Why struct method? The main advantage is that all the data related to the instance is put inside the impl
block rather than putting it in different places.
Example
The example below shows declares a method name_code
function within the impl
construct:
output
Quiz
Test your understanding of methods of structs.
Last updated a year ago.