Code Fix

初級E0596: cannot borrow as mutable の原因と直し方 › パターン4

E0596: cannot borrow as mutable の原因と直し方

mutを付けずに宣言した変数を、&mutで可変参照として渡そうとするとE0596エラーになります。

 1  fn reset(n: &mut i32) {
 2      *n = 0;
 3  }
 4  
 5  fn main() {
 6      let ______counter = 5;
               ^
 7      reset(&mut counter);
 8      println!("{}", counter);
 9  }
error[E0596]: cannot borrow `counter` as mutable, as it is not declared as mutable

空欄を埋めて実行を通す

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

E0596: cannot borrow as mutable の原因と直し方

値を変更する関数に渡す変数は、宣言時からmutにしておく必要があります。

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

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