struct method#
What is a method?#
A method is essentially the same as a function, except that it is included within a struct.
Let’s learn how to define a method.
In the following example, a Person struct is defined as struct Person { ~~~ }.
In impl Person, impl stands for implementation.
The functions created inside impl { ~~~ } are methods.
A method is created with fn speak(self) { ~~~ }, where self is taken as the first parameter.self refers to the struct itself, struct Person.
The first parameter of a method must be self; otherwise, a compile error will occur.
The line println!("hi, {}", self.name); prints self.name.
Here, self.name refers to name: String inside struct Person { name: String, }.
After creating an instance with let person = Person{ ~~~ };, you can call the method with person.speak().