Rust Methods
Methods
In the Structs chapter, you used a struct to group related data, like the name and age of a person.
Often, you also want functions that work with that data, for example a function that prints a greeting, or checks if the person can vote. A function that belongs to a struct is called a method.
Methods are written inside an impl block (short for implementation), after the struct:
Example
struct Person {
name: String,
age: u32,
}
impl Person {
fn greet(&self) {
println!("Hello, my name is {} and I am {} years old.", self.name, self.age);
}
}
fn main() {
let user = Person {
name: String::from("John"),
age: 35,
};
user.greet();
}
Try it Yourself »
Example explained:
impl Personstarts a block with methods for thePersonstructfn greet(&self)creates a method calledgreet. The first parameter,&self, is the object that the method is called on- Inside the method,
self.nameandself.ageread the fields of that object user.greet()calls the method with dot syntax, just like you access a field
The & in &self means that the method borrows the object. It can read the fields, but it does not take ownership, so you can still use user after the call.
Methods That Return a Value
Just like other functions, a method can return a value. Use -> followed by the type of the value:
Example
impl Person {
fn can_vote(&self) -> bool {
self.age >= 18
}
}
let user = Person {
name: String::from("Liam"),
age: 16,
};
println!("Can {} vote? {}", user.name, user.can_vote());
Try it Yourself »
Liam is 16, so can_vote() returns false.
Change Fields With &mut self
To change the fields of an object, the method must use &mut self instead of &self:
Example
impl Person {
fn have_birthday(&mut self) {
self.age += 1;
}
}
let mut user = Person {
name: String::from("Jenny"),
age: 29,
};
user.have_birthday();
println!("{} is now {} years old.", user.name, user.age);
Try it Yourself »
The object must also be mutable (let mut). If you forget mut, the code will not compile:
Example
let user = Person {
name: String::from("Jenny"),
age: 29,
};
user.have_birthday(); // Error
Try it Yourself »
Associated Functions
All functions inside an impl block are called associated functions, because they belong to the struct. A function that does not have self as its first parameter is not a method, because it is not called on an object.
A common example is a function called new(), which creates a new object. You call it with the struct name and ::, just like String::from():
Example
impl Person {
fn new(name: &str, age: u32) -> Person {
Person {
name: String::from(name),
age: age,
}
}
}
let user = Person::new("John", 35);
println!("{} is {} years old.", user.name, user.age);
Try it Yourself »
Note: Rust does not have special constructors like some other languages. new is just a normal name that Rust programmers use for functions that create an object.
Putting It Together
An impl block can have many methods. Here, a player starts with 0 points, gets points two times, and then shows the score:
Example
struct Player {
name: String,
score: u32,
}
impl Player {
fn new(name: &str) -> Player {
Player {
name: String::from(name),
score: 0,
}
}
fn add_points(&mut self, points: u32) {
self.score += points;
}
fn show(&self) {
println!("{} has {} points", self.name, self.score);
}
}
fn main() {
let mut player = Player::new("Jenny");
player.add_points(10);
player.add_points(5);
player.show();
}
Try it Yourself »
Summary
| First parameter | What it can do | How to call it |
|---|---|---|
&self |
Read the fields | user.greet() |
&mut self |
Read and change the fields (the object must be mut) |
user.have_birthday() |
No self |
Associated function, often used to create an object | Person::new("John", 35) |