immutable borrow occurs hereでD問題落とした話【Rust】

June 21, 2025, 2 p.m. edited June 21, 2025, 2:18 p.m.

#Rust 

ロジックはできてたのに、何。

検証用として、 src/main.rs

fn main() {
    let mut a = vec![Vec::new(); 10];
    a[5].push(a[0].len());
    println!("work");
}

とすると

$ cargo run
   Compiling immutable_borrow_test v0.1.0
error[E0502]: cannot borrow `a` as immutable because it is also borrowed as mutable
 --> src/main.rs:3:15
  |
3 |     a[5].push(a[0].len());
  |     -    ---- ^ immutable borrow occurs here
  |     |    |
  |     |    mutable borrow later used by call
  |     mutable borrow occurs here

For more information about this error, try `rustc --explain E0502`.
error: could not compile `immutable_borrow_test` (bin "immutable_borrow_test") due to previous error

それならと、てきとうに

fn main() {
    let mut a = vec![Vec::new(); 10];
    let hoge = a[0].len();
    a[5].push(hoge);
    println!("work");
}

とすると

$ cargo run
   Compiling immutable_borrow_test v0.1.0
    Finished dev [unoptimized + debuginfo] target(s) in 0.58s
     Running `target/debug/immutable_borrow_test`
work

は????何が違うというんですか?????

理由

同一のデータに対する可変参照 (5番目だが同じaというVecへの変更操作) と不変参照 (0番目だが同じaというVecへの参照) が同時に存在してはいけないという借用規則に違反していたため。

……いや、それはそうなんだけどさああ!!!(大声)
a[0].len() はその時点で完了しているわけだから、同時とは言えなくないですか?!?!ねえ!!!!

…はあ、Rustにとっては同時なんですか、そうですか、わかりましたよ……