cannot borrow as mutable because it is also borrowed as immutable
Rustの借用チェッカーによるエラーの解決方法
概要
Rustの借用チェッカー(borrow checker)は、メモリ安全性を保証するためのコンパイル時チェック機構です。所有権と借用のルールに違反するとコンパイルエラーになります。
エラーメッセージ
error[E0502]: cannot borrow `vec` as mutable because it is also borrowed as immutable
--> src/main.rs:5:5
|
3 | let first = &vec[0];
| --- immutable borrow occurs here
4 |
5 | vec.push(4);
| ^^^^^^^^^^^ mutable borrow occurs here
6 |
7 | println!("{}", first);
| ----- immutable borrow later used here
error[E0499]: cannot borrow `x` as mutable more than once at a time
借用のルール
- 複数の不変参照(&T) は同時に存在できる
- 可変参照(&mut T) は同時に1つだけ
- 不変参照と可変参照 は同時に存在できない
- 参照は所有者より長く生存できない
よくあるエラーと解決策
1. 不変参照と可変参照の競合
| |
2. ループ中の変更
| |
3. 構造体のフィールドを同時に借用
| |
4. 関数からの参照返却
| |
5. クロージャと借用
| |
解決パターン
1. Cloneを使う
| |
2. スコープを分ける
| |
3. RefCell(実行時借用チェック)
| |
4. Rc<RefCell>(共有可変参照)
| |
5. 内部可変性パターン
| |
ライフタイムエラー
| |
デバッグのコツ
| |
関連エラー
関連エラー
Rust の他のエラー
called `Option::unwrap()` on a `None` value
error[E0382]: borrow of moved value
error[E0507]: cannot move out of 'x' which is behind a shared reference
error[E0599]: no method named 'x' found for struct
Rust: cannot borrow as mutable
Rust: cannot borrow as mutable because it is also borrowed as immutable
この記事は役に立ちましたか?