In the below example, I mutably borrow p
twice, but the program compiles. Why is this?
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
x_vel: i32,
y_vel: i32,
}
fn step(p: &mut Point) {
p.x += p.x_vel;
p.y += p.y_vel;
}
fn main() {
println!("Hello, world!");
let mut p = Point {
x: 0,
y: 0,
x_vel: 3,
y_vel: 2,
};
println!("{:?}", p);
step(&mut p);
println!("{:?}", p);
step(&mut p);
println!("{:?}", p);
}
edit
To make it very clear two mutable borrows are happening, see the below code. This also compiles without error. Why is this allowed?
println!("{:?}", p);
let pref = &mut p;
step(pref);
println!("{:?}", p);
let pref2 = &mut p;
step(pref2);
println!("{:?}", p);