Module lessons (2/2)
Methods and impl Blocks
In Rust, methods are similar to functions, but they are defined within the context of a struct (or an enum or trait), and their first parameter is always self, which represents the instance of the struct the method is being called on.
Defining Methods with impl
To define methods on a struct, we use an impl (implementation) block with the struct's name:
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
// This is an instance method. It takes &self for reading.
fn area(&self) -> u32 {
self.width * self.height
}
}
fn main() {
let rect = Rectangle { width: 30, height: 50 };
// Call the method using dot notation
println!("The area is: {}", rect.area());
}
Associated (Static) Functions
Functions defined within an impl block that do not accept self as their first parameter are called associated functions (equivalent to static methods in other languages).
They are often used as constructors to return new instances of the struct. To call them, use the double colon :: syntax:
impl Rectangle {
// Associated function
fn square(size: u32) -> Rectangle {
Rectangle {
width: size,
height: size,
}
}
}
fn main() {
// Call the associated function
let sq = Rectangle::square(10);
}
Methods that Modify State: &mut self
If a method needs to modify the fields of the struct, it must declare its first parameter as &mut self. The instance itself on which the method is called must be declared as mutable (let mut):
impl Rectangle {
fn double_size(&mut self) {
self.width *= 2;
self.height *= 2;
}
}
Try it yourself
Complete the impl block by defining the area method that takes &self and returns u32 (the multiplication of width and height).
Show hint
Write `fn area(&self) -> u32 { self.width \* self.height }`inside the`impl Rectangle` block.
Solution available after 3 attempts
Define the square associated function inside impl Rectangle, which receives size: u32 and returns a Rectangle instance with width and height equal to size.
Show hint
Write `fn square(size: u32) -> Rectangle { Rectangle { width: size, height: size } }`inside the`impl` block.
Solution available after 3 attempts
Add the scale mutator method to Rectangle inside the impl block. The scale method must take a mutable reference to self (&mut self) and a factor: u32 parameter, and multiply both the width and height of Rectangle by factor.
Show hint
Implement `fn scale(&mut self, factor: u32)`to update`self.width`and`self.height`by multiplying them by`factor`.
Solution available after 3 attempts