Method Syntax
Method Syntax
Because they begin with the fn keyword and end with the function name, methods and functions are similar. The parameters and return value are also included in methods. The method syntax differs from the standard function, though, when the method is declared inside the struct context. Such methods usually have self as their first parameter, which stands for the instance that the function is called on.
Defining methods
When the method is declared in the struct context, let’s define it.
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
The method is defined inside the implementation block, or impl block, when it is declared within the struct context.
impl Square
{
fn area(&self)->u32
{
self.a * self.a
}
}
Being oneself in the signature and across the body is the first requirement.
Here, we invoke the area() function using the method syntax. The method name, parameter, any arguments, and the dot operator come after the instance of the method syntax.
square.area();
where the function name is area() and the square represents an instance.
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 primary benefit of utilizing method syntax over functions is that all instance-related data is contained inside the impl block as opposed to being placed in various locations that we supply.