Skip to content

方法

方法与函数类似:它们使用 fn 关键字和名称声明,可以拥有参数和返回值,同时包含在某处调用该方法时会执行的代码。

不同之处在于方法的第一个参数总是 self,方法只能由结构体实例进行调用。

方法使用 impl 关键字表示,后面为结构体名。这个 impl 块中的所有内容都将与结构体类型相关联。

方法定义示例:

rust
#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

fn main() {
    let rect1 = Rectangle {
        width: 30,
        height: 50,
    };

    println!(
        "The area of the rectangle is {} square pixels.",
        rect1.area()
    );
}

更多结构体方法的知识将在进阶知识中详细讲解。