以下是一個簡單的模擬,其中一個場是一個矩形區域,其中有兩個球在其中彈跳。 Field
結構有一個update
方法,該方法在每個球上調用update
。球的方法update
需要根據其速度移動。但他們也需要對方的反應,以及現場:將可變自引用傳遞給擁有對象的方法
fn main() {
let mut field = Field::new(Vector2d { x: 100, y: 100 });
field.update();
}
#[derive(Copy, Clone)]
struct Vector2d {
x: i32,
y: i32,
}
struct Ball {
radius: i32,
position: Vector2d,
velocity: Vector2d,
}
impl Ball {
fn new(radius: i32, position: Vector2d, velocity: Vector2d) -> Ball {
Ball {
radius: radius,
position: position,
velocity: velocity,
}
}
fn update(&mut self, field: &Field) {
// check collisions with walls
// and other objects
}
}
struct Field {
size: Vector2d,
balls: [Ball; 2],
}
impl Field {
fn new(size: Vector2d) -> Field {
let position_1 = Vector2d {
x: size.x/3,
y: size.y/3,
};
let velocity_1 = Vector2d { x: 1, y: 1 };
let position_2 = Vector2d {
x: size.x * 2/3,
y: size.y * 2/3,
};
let velocity_2 = Vector2d { x: -1, y: -1 };
let ball_1 = Ball::new(1, position_1, velocity_1);
let ball_2 = Ball::new(1, position_2, velocity_2);
Field {
size: size,
balls: [ball_1, ball_2],
}
}
fn update(&mut self) {
// this does not compile
self.balls[0].update(self);
self.balls[1].update(self);
}
}
的邊界如何獲取有關界與其它球給Ball
結構的更新功能的信息?在Field::update
這些線路不進行編譯:
self.balls[0].update(self);
self.balls[1].update(self);
給予以下錯誤:
error[E0502]: cannot borrow `*self` as immutable because `self.balls[..]` is also borrowed as mutable
--> src/main.rs:62:30
|
62 | self.balls[0].update(self);
| ------------- ^^^^- mutable borrow ends here
| | |
| | immutable borrow occurs here
| mutable borrow occurs here
我理解,但我不知道怎麼去解決這個問題。
是啊,這將工作。男人,魯斯特真的讓我對我的計劃方式有不同的想法。 –