In Rust, there are two main types of references:
&T): provide read-only access.&mut T): allow modifying the value they point to.Rules:
Syntax examples:
fn read(val: &i32) { println!("{}", val); } fn write(val: &mut i32) { *val += 1; } let mut x = 5; read(&x); write(&mut x);
Question: Can you create two mutable references to one variable in different scopes of the same function?
Answer: No, even if the references are created in different blocks, the scope for borrow checking covers the entire function or variable unless the compiler can prove that the references do not overlap. This often results in compile errors:
let mut x = 10; let r1 = &mut x; { let r2 = &mut x; // error! }
Story
In parser development, a developer tried to store both a mutable and an immutable reference to the same buffer for optimization of reading and writing. As a result, the code would not compile, and after "bypassing" the rule through unsafe code, data leakage bugs appeared.
Story
At the start of a data processing project, one of the participants did not "reanalyze borrow checker" for complex code with nested scopes. As a result, due to overlapping references, the classic "cannot borrow as mutable because it's also borrowed as immutable" error arose without an explicit indication of the problem's location in the source code.
Story
In multithreaded code, plain references were used to access shared data. When trying to modify data in parallel threads, unexpected compile errors and data races occurred when bypassing the borrow checker via unsafe code.