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().
struct Person {
name: String,
}
impl Person {
fn speak(self) {
println!("hi, {}", self.name);
}
}
fn main() {
let person = Person{
name: String::from("semonan.com"),
};
person.speak()
}Passing multiple parameters to a method#
Let’s learn how to receive more parameters in a method besides self.
Inside impl Person { ~~~ }, the methods speak_a and speak_b are created.
In fn speak_a(&self, first_name: &String), a first_name parameter of String type is taken to the right of self.
In fn speak_b(&self, first_name: &String, last_name: &String), a last_name parameter of String type is taken to the right of self and first_name.
In this way, multiple parameters can be passed by separating them with commas (,).
The received parameters can be used like println!("hi, {}", first_name);.
You can pass parameters when calling the method, such as person.speak_a(&first_name);.
struct Person {
}
impl Person {
fn speak_a(&self, first_name:&String) {
println!("hi, {}", first_name);
}
fn speak_b(&self, first_name:&String, last_name:&String ) {
println!("hi, {}, {}", first_name, last_name);
}
}
fn main() {
let person = Person{};
let first_name = String::from("simon");
let last_name = String::from("kay");
person.speak_a(&first_name);
person.speak_b(&first_name, &last_name);
}