Code Fix

中級E0502: cannot borrow as mutable because it is also borrowed as immutable › パターン4

E0502: cannot borrow as mutable because it is also borrowed as immutable

不変参照が生きている(後で使われる)間に、同じ変数を可変で借用しようとするとE0502エラーになります。

 1  fn main() {
 2      let mut prices = vec![100, 200];
 3      let cheapest = &prices[0];
 4      ________________
                ^
 5      println!("{}", cheapest);
 6  }
error[E0502]: cannot borrow `prices` as mutable because it is also borrowed as immutable

空欄を埋めて実行を通す

広告
広告スロット(未設定)

E0502: cannot borrow as mutable because it is also borrowed as immutable

Rustの借用規則は「不変参照は何個でも、可変参照は同時に1つだけ」を強制します。

このエラーの解説と類題をまとめて見る →

広告
広告スロット(未設定)