问题复现,假设我们有一个简单的 Point 结构体:
struct Point {
x: f64,
y: f64,
}
impl Point {
pub fn x_mut(&mut self) -> &mut f64 {
&mut self.x
}
pub fn y_mut(&mut self) -> &mut f64 {
&mut self.y
}
}
当我们尝试同时获取 x 和 y 的可变引用时:
fn main() {
let mut point = Point { x: 1.0, y: 2.0 };
// 尝试同时获取两个字段的可变引用
let x_ref = point.x_mut();
let y_ref = point.y_mut(); // 编译错误!
*x_ref *= 2.0;
*y_ref *= 2.0;
}
1:使用结构体解构
fn main() {
let mut point = Point { x: 1.0, y: 2.0 };
// 使用代码块限制借用的生命周期
{
let Point { ref mut x, ref mut y } = &mut point;
*x *= 2.0;
*y *= 2.0;
}
println!("Point: ({}, {})", point.x, point.y);
}
2:直接访问字段
fn main() {
let mut point = Point { x: 1.0, y: 2.0 };
// 使用代码块限制可变引用的作用域
{
let x_ref = &mut point.x;
let y_ref = &mut point.y;
*x_ref *= 2.0;
*y_ref *= 2.0;
}
println!("Point: ({}, {})", point.x, point.y);
}
3:返回多个可变引用的元组
impl Point {
// 同时返回 x 和 y 的可变引用
pub fn x_y_mut(&mut self) -> (&mut f64, &mut f64) {
(&mut self.x, &mut self.y)
}
}
fn main() {
let mut point = Point { x: 1.0, y: 2.0 };
{
let (x_ref, y_ref) = point.x_y_mut();
*x_ref *= 2.0;
*y_ref *= 2.0;
}
println!("Point: ({}, {})", point.x, point.y);
}