Blue7
Blue7

Reputation: 2044

Why can I mutably borrow twice in this example?

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); 

Upvotes: 0

Views: 208

Answers (1)

ozan k
ozan k

Reputation: 500

First mutable borrow ends when execution returns from step to main function. So the second borrow is possible because there is no other borrow at that moment.

Upvotes: 4

Related Questions