error[E0382]: borrow of moved value
Rustで所有権が移動した後の値を借用しようとした際のコンパイルエラー
概要
Rustで値の所有権が別の変数や関数に移動(ムーブ)した後に、その元の値を借用または使用しようとした際に発生するコンパイルエラーです。
エラーメッセージ
error[E0382]: borrow of moved value: `s`
--> src/main.rs:5:20
|
2 | let s = String::from("hello");
| - move occurs because `s` has type `String`, which does not implement the `Copy` trait
3 | let s2 = s;
| - value moved here
4 |
5 | println!("{}", s);
| ^ value borrowed here after move
原因
- 変数への代入: 値を別の変数に代入すると所有権が移動
- 関数への引数渡し: 関数に値を渡すと所有権が移動
- クロージャでのキャプチャ: moveクロージャで値がキャプチャされる
- Copy未実装: 型がCopyトレイトを実装していない
解決策
1. clone()で複製
| |
2. 参照を渡す
| |
3. 所有権を返す
| |
4. Copy型を使用
| |
5. Rcで共有所有権
| |
6. クロージャでの対処
| |
7. スコープを分離
| |
8. Option::take()で所有権を取得
| |
Copy型とMove型
| |
よくある間違い
- 関数に値を渡した後で元の変数を使おうとする
- forループで値をイテレートした後でコレクションを使う
- if letやmatchで値をムーブした後で使おうとする
関連エラー
参考リンク
Rust の他のエラー
cannot borrow as mutable because it is also borrowed as immutable
called `Option::unwrap()` on a `None` 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
この記事は役に立ちましたか?