Why is one mutable borrow allowed while this could also cause a race condition?

Hello,

I know that the below code does as described in the comments. But why can the Rust compiler
"catch" a potential race condition between 2 variables but not between 3 or more? Thanks!

fn main() {
    let mut x = 2;
    let y = &mut x; // 1st borrow works
    let z = &mut x; // 2nd borrow throws an error
    *y += 1;
    println!("{}",x);
}

You mean that usage of y, being a mutable borrow of x, could race with usage of x itself? It can't, since we can't use x while y is still active:

fn main() {
    let mut x = 2;
    let y = &mut x;
    x = 1; // error: cannot assign to `x` because it is borrowed
    *y += 1;
    println!("{}", x);
}
2 Likes

oh youre right I forgot about that, thanks!

FWIW I'm being pedantic but this is not a race condition -- you would need threads and as soon as you attempt to send the variable across a thread boundary you'd get an error. This is just a generic violation of Rust's "one mutable reference"/noalias rule.

thanks :slight_smile:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.