Chuyển đến nội dung chính
eLearner.app
Mô-đun 4 · Bài học 2 trong tổng số 28/14 trong khóa học~12 min
Bài học theo mô-đun (2/2)

Phương thức và khối impl

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:

Code
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:

Code
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):

Code
impl Rectangle {
    fn double_size(&mut self) {
        self.width *= 2;
        self.height *= 2;
    }
}

Try it yourself

tập thể dục#rust.m4.l2.e1
Nỗ lực: 0Đang tải…

Complete the impl block by defining the area method that takes &self and returns u32 (the multiplication of width and height).

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Write `fn area(&self) -> u32 { self.width \* self.height }`inside the`impl Rectangle` block.

Giải pháp khả dụng sau 3 lần thử

tập thể dục#rust.m4.l2.e2
Nỗ lực: 0Đang tải…

Define the square associated function inside impl Rectangle, which receives size: u32 and returns a Rectangle instance with width and height equal to size.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Write `fn square(size: u32) -> Rectangle { Rectangle { width: size, height: size } }`inside the`impl` block.

Giải pháp khả dụng sau 3 lần thử

tập thể dục#rust.m4.l2.e3
Nỗ lực: 0Đang tải…

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.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Implement `fn scale(&mut self, factor: u32)`to update`self.width`and`self.height`by multiplying them by`factor`.

Giải pháp khả dụng sau 3 lần thử