In Rust, methods are a bit different from functions. Actually, a method is a function that performs some operation on a struct’s instance.
Use the impl
keyword
Mention the name of the struct that this method is associated with
Write a normal function inside the impl
body
Write self
, &self
, or &mut self
as the first parameter
// Declare a struct:
struct Student {
id: i32,
name: String,
marks: i8,
}
// Declare its method:
impl Student {
fn penalize(&mut self) {
self.marks -= 5;
}
}
&mut self
is used instead of&self
because the value ofmarks
is changed by the function, which requires a mutable reference.
The penalize()
method will be called in the following way:
struct Student {id: i32,name: String,marks: i8,}impl Student{fn penalize(&mut self){self.marks -= 5;}}fn main() {let mut s1 = Student {id: 500,name: String::from("Hanna"),marks: 95};println!("Previous marks = {}", s1.marks);// Call penalize() on s1:s1.penalize();// Display new value of marks:println!("New marks = {}", s1.marks);}
Note that a mutable reference of the instance is not explicitly passed to the method. This is because of a feature known as automatic referencing and dereferencing. Simply put, it’s a cleaner way to write code. Without this feature, the call would have been made like this:
(&mut s1).penalize(); // For a mutable reference
(&s1).penalize(); // For an immutable reference
// Both of the above calls can be made automatically by using:
s1.penalize();
Free Resources