Home » Rust Struct Method Syntax

Rust Struct Method Syntax

by Online Tutorials Library

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.

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.

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.

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.


Next TopicWhat is enum

You may also like