Industrial Training




Method syntax

Methods are similar to functions as they contain the fn keyword at the starting and then function name. Methods also contain the parameters and return value. However, when the method is declared within the struct context, then the method syntax varies from the normal function. The first parameter of such methods is always self, which represents the instance on which the function is called upon.


Defining methods


Let's define the method when the method is declared in the struct context.


 struct Square  
{  
a : u32,  
}  
impl Square  
{  
fn area(&self)->u32  
{  
self.a * self.a  
}  
}  
  
fn main()  
{  
let square = Square{a:10};  
print!("Area of square is {}", square.area());  
}  

Output:
Area of square is 100

When the method is declared within the struct context, then we defin the method inside the implementation block, i.e., impl block.


 impl Square  
{  
fn area(&self)->u32  
{  
self.a * self.a  
}  
}  

The first parameter is to be self in the signature and everywhere within the body.
Here, we use the method syntax to call the area() function. The method syntax is an instance followed by the dot operator, method name, parameter, and any arguments.


square.area();  

Where the square is an instance and area() is the function name.


\

Note: If we want to change the instance on which the method is called upon, then we use &mut self rather than &self as the first parameter.


An Advantage of method syntax:

The main advantage of using method syntax over functions is that all the data related to the instance is placed inside the impl block rather than putting in different places that we provide.




Hi I am Pluto.