方法
约 318 字大约 1 分钟
2025-09-26
方法即定义在结构体中的函数,它们的第一个参数总是 self 用于表示调用该方法的结构体实例
定义方法
方法需要放在 impl 块中实现,在使用时通过 instance.method() 即可调用
定义方法
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
fn main() {
let rect = Rectangle { width: 30, height: 50 };
println!("area = {}", rect.area());
}重要
&self其实是self: &Self的缩写,而Self表示的是当前impl块的类型的别名- 有
self参数的才是“方法”;没有self的是关联函数,二者调用形式不同
关联函数
所有在 impl 中定义的不带 self 参数的函数被称为 关联函数,因为它们与 impl 后面命名的类型相关。它们常被用作返回新实例的构造函数(通常命名为 new),调用时用 TypeName::new() 这样的 :: 命名空间语法
impl Rectangle {
fn new(width: u32, height: u32) -> Self {
Self {
width,
height,
}
}
}