From Rust documentations:
mutable references have one big restriction: you can have only one mutable reference to a particular piece of data in a particular scope.
The example in the docs does support this statement:
let mut s = String::from("hello");
let r1 = &mut s;
let r2 = &mut s;
println!("{}, {}", r1, r2);
But this is a bit misleading to me. When print statement in the last line is removed the program compiles and runs fine (although with a couple of warnings). Later in the docs they say this is how rust deals with data races. I haven't reached the point where they explain threads and parallel programming but I guess it's still worthwhile to ask how are we preventing the data race in the following case:
fn main() {
let mut name: String = String::from("Devashish");
// assume that fun1 was called from a new thread
fun1(&mut name);
// fun1 and fun2 are being executed in parallel at this point
fun2(&mut name);
}
fn fun1(re: &mut String) {
println!("From fun1: {}", re);
}
fn fun2(re: &mut String) {
println!("From fun2: {}", re);
}
How are we preventing data race in the case above?