定义区别
- 结构体方法:定义在结构体内部,使用
impl
块。第一个参数通常是self
,表示结构体实例。
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
- 关联函数:同样定义在
impl
块中,但第一个参数不是self
。它不依赖于结构体的实例。
struct Point {
x: i32,
y: i32,
}
impl Point {
fn origin() -> Point {
Point { x: 0, y: 0 }
}
}
调用方式区别
let rect = Rectangle { width: 10, height: 5 };
let area = rect.area();
let p = Point::origin();
参数传递区别
- 结构体方法:第一个参数是结构体实例的引用(如
&self
、&mut self
或self
),这样可以访问和修改结构体的字段。
impl Rectangle {
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
let rect1 = Rectangle { width: 10, height: 5 };
let rect2 = Rectangle { width: 8, height: 3 };
let can_hold = rect1.can_hold(&rect2);
- 关联函数:参数根据函数定义而定,没有特殊的与结构体实例相关的参数要求。
impl Point {
fn new(x: i32, y: i32) -> Point {
Point { x, y }
}
}
let p = Point::new(3, 4);