跳转到主要内容
模块 4 · 第 2 课(共 2)课程中的8/14~12 min
模块课程(2/2)

方法和 impl 块

在 Rust 中,方法类似于函数,但它们是在结构体(或枚举或特征)的上下文中定义的,并且它们的第一个参数始终是 self,它表示调用该方法的结构体的实例。

使用 impl 定义方法

要在结构体上定义方法,我们使用带有结构体名称的 impl (实现)块:

Rust
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());
}

关联(静态)函数

在 impl 块中定义的函数不接受 self 作为其第一个参数,称为关联函数(相当于其他语言中的静态方法)。

它们通常用作构造函数来返回结构的新实例。要调用它们,请使用双冒号 :: 语法:

Rust
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);
}

修改状态的方法:&mut self

如果方法需要修改结构体的字段,则必须将其第一个参数声明为 &mut self。调用该方法的实例本身必须声明为可变的 (let mut):

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

自己尝试一下

锻炼#rust.m4.l2.e1
尝试:0加载中...

通过定义接受 &self 并返回 u32(宽度和高度的乘积)的区域方法来完成 impl 块。

正在加载编辑器...
显示提示

在“impl Rectangle”块内写入“fn area(&self) -> u32 { self.width \* self.height }”。

3 次尝试后可用的解决方案

锻炼#rust.m4.l2.e2
尝试:0加载中...

在 impl Rectangle 内部定义正方形关联函数,该函数接收 size: u32 并返回一个宽度和高度等于 size 的 Rectangle 实例。

正在加载编辑器...
显示提示

在“impl”块中写入“fn square(size: u32) -> Rectangle { Rectangle { width: size, height: size } }”。

3 次尝试后可用的解决方案

锻炼#rust.m4.l2.e3
尝试:0加载中...

将scale mutator 方法添加到impl 块内的矩形。 scale 方法必须采用对 self (&mut self) 的可变引用和一个 factor: u32 参数,并将 Rectangle 的宽度和高度乘以因子。

正在加载编辑器...
显示提示

实现“fn scale(&mut self, factor: u32)”以通过将“self.width”和“self.height”乘以“factor”来更新它们。

3 次尝试后可用的解决方案