// 定义Point结构体
struct Point {
x: i32,
y: i32,
}
// 为Point结构体实现+=运算符
impl std::ops::AddAssign for Point {
fn add_assign(&mut self, other: Self) {
self.x += other.x;
self.y += other.y;
}
}
// 定义函数接收两个Point实例并返回相加结果
fn add_points(p1: Point, p2: Point) -> Point {
let mut result = p1;
result += p2;
result
}
所有权和借用问题及解决
- 所有权:
- 在
add_points
函数中,p1
和p2
作为参数传递,所有权被转移到函数中。这意味着在函数内部,函数拥有这两个Point
实例的所有权。
- 函数返回
result
,此时result
的所有权被转移给调用者。
- 借用:
- 在实现
AddAssign
trait时,self
使用&mut
引用,这是因为+=
运算符通常会修改调用它的实例。other
是值传递,因为它的所有权会被转移到add_assign
方法内部,然后被消耗,这样可以避免不必要的复制。通过这种方式,既满足了对self
的修改需求,又合理处理了other
的所有权,避免了所有权和借用规则的冲突。