Defining methods for a struct
V allows us to define methods for a struct. A method is a function with a special receiver argument that appears between fn
and the method name. They allow us to add functions to a struct in a convenient manner. Methods are the kind of functions that access the properties of the struct to perform some routine. To define a method for a struct, follow the syntax shown here:
fn (r RECEIVER_TYPE) METHOD_NAME(OPTIONAL_INPUT_ARGUMENTS) RETURN_TYPE { METHOD BODY }
In the preceding syntax, the RECEIVER_TYPE
indicates the name of the struct to which the method belongs. If you are familiar with the C# programming language, this feature is similar to the concept of extension methods in C#. During runtime, the methods of a struct have access to the values held by the fields of the struct. Therefore, the methods help to evaluate logic or perform desired operations with the struct fields.
Note
The methods that...