Rust 中没有 class,方法通过 impl 块定义在结构体 / 枚举 上,第一个参数必须是 self 相关形式。
1. 基本方法:&self(只读)
-
不获取所有权,只读取字段
-
最常用
struct Rectangle {
width: u32,
height: u32,
}impl Rectangle {
// 方法:计算面积
fn area(&self) -> u32 {
self.width * self.height
}
}fn main() {
let rect = Rectangle { width: 10, height: 20 };
println!("{}", rect.area()); // 200
}
2. 可变方法:&mut self(可修改)
需要修改实例时使用。
impl Rectangle {
fn set_width(&mut self, w: u32) {
self.width = w;
}
}
fn main() {
let mut rect = Rectangle { width: 10, height: 20 };
rect.set_width(30);
}
3. 拿走所有权:self
方法执行后实例不再可用,常用于消耗、转换实例。
impl Rectangle {
fn into_tuple(self) -> (u32, u32) {
(self.width, self.height)
}
}
4. 关联函数(无 self)
-
不属于实例,属于类型
-
常用作构造器
newimpl Rectangle {
fn new(w: u32, h: u32) -> Self {
Rectangle { width: w, height: h }
}
}// 调用
let r = Rectangle::new(10, 20);
5. 方法名与字段同名(访问器)
Rust 允许方法名和字段同名,调用时靠是否带括号区分。
impl Rectangle {
fn width(&self) -> u32 {
self.width
}
}
// 调用
r.width(); // 方法
r.width; // 字段
常用于实现 getter,配合私有字段做封装。
6. 自动引用 / 解引用
调用方法时 Rust 会自动加 & / &mut,不用手动写:
rect.area();
// 等价于
(&rect).area();
7. 多个 impl 块
同一个类型可以拆成多个 impl,方便代码组织。
impl Rectangle { fn area(&self) -> u32 { ... } }
impl Rectangle { fn can_hold(&self, other: &Self) -> bool { ... } }
8. 枚举也能定义方法
enum Shape {
Rect(u32, u32),
Circle(u32),
}
impl Shape {
fn area(&self) -> u32 {
match self {
Shape::Rect(w, h) => w * h,
Shape::Circle(r) => 3 * r * r,
}
}
}
速记
&self只读(最常用)&mut self可修改self拿走所有权::new()构造器(关联函数)- 方法 = 数据(struct/enum) + 行为(impl)