I am new to Rust (Moving from C++) and I cannot seem to wrap my head around the Rust’s compile time borrowchecker for this specific case:
Using a struct
When I create a struct and mutably borrow references of the two fields within the same scope, the code is compiled and the expected output is given:
struct Node2{
value: i32,
value2: i32,
}
fn main() {
let mut node = Node2{value: 10, value2: 10};
let a = &mut node.value2;
let b = &mut node.value;
*a = 5;
*b = 4;
println!("a: {}, b: {}", a, b);
prints: a: 5, b: 4
Using an array
If I try to do the same thing with arrays, this doesn’t work anymore and the borrow checker will throw me an error.
Comming from C++, this seems counter intuitive to me, because structs are allocated as contiguous memory (Same as Arrays / vectors) and the fields are accessed as offsets (Exactly same as arrays), so there is no overall difference in the way the data is accessed—It is basically just a different view to the same data.
Here is the code:
let mut item_vector = vec![1, 2, 3, 4, 5];
let av = &mut item_vector[0];
let bv = &mut item_vector[1];
*av = 10;
*bv = 20;
println!("av: {}, bv: {}", av, bv);
and it fails with the following error:
|
24 | let av = &mut item_vector[0];
| ----------- first mutable borrow occurs here
25 | let bv = &mut item_vector[1];
| ^^^^^^^^^^^ second mutable borrow occurs here
26 |
27 | *av = 10;
| -------- first borrow later used here
Reason for the confusion
I understand that mut is supposed to be an exclusive write access, but I don’t understand why it is different for structs / arrays.
Surely any condition racing that a struct is vulnerable to, would make an array vulnerable in the same way.
With my limited knowedlge, it seems inconsistent.
I would appreciate a run down of why this is happeing and what was the design decision behind this, (Why does borrowing a single element from an array count as if the whole array was borrowed by the checker and why does the same not apply for a struct)