called `Option::unwrap()` on a `None` value
RustでNone値に対してunwrap()を呼び出した際に発生するpanicエラー
概要
called Option::unwrap() on a None value は、RustでOption型のNone値に対してunwrap()を呼び出した際に発生するpanicです。
エラーメッセージ
thread 'main' panicked at 'called `Option::unwrap()` on a `None` value'
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ...'
原因
1. Noneに対するunwrap()
| |
2. 見つからない要素への直接アクセス
| |
3. HashMapの存在しないキー
| |
解決策
1. unwrap_or でデフォルト値を指定
| |
2. unwrap_or_else で遅延評価
| |
3. if let でパターンマッチング
| |
4. match で明示的に処理
| |
5. ? 演算子で早期リターン
| |
6. expect でカスタムエラーメッセージ
| |
7. ok_or でResultに変換
| |
unwrapを使って良い場面
| |
関連エラー
関連エラー
Rust の他のエラー
cannot borrow as mutable because it is also borrowed as immutable
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
この記事は役に立ちましたか?