panic: runtime error: index out of range / nil pointer dereference
Goでランタイムパニックが発生した場合の対処法
概要
Goの panic はプログラムの実行を停止させる深刻なエラーです。配列の範囲外アクセスやnilポインタの参照解除などで発生します。
エラーメッセージ
panic: runtime error: index out of range [5] with length 3
goroutine 1 [running]:
main.main()
/app/main.go:10 +0x45
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x...]
よくあるpanic
1. index out of range
| |
2. nil pointer dereference
| |
3. nil map への書き込み
| |
4. nil channel
| |
5. 閉じたchannelへの送信
| |
解決策
1. インデックスアクセスの安全化
| |
2. nilチェック
| |
3. recoverでpanicを捕捉
| |
4. mapの安全なアクセス
| |
5. インターフェースのnilチェック
| |
よくあるパターン
HTTPハンドラ
| |
JSONパース
| |
goroutine内のpanic
| |
デバッグ
| |
| |
関連エラー
関連エラー
Go の他のエラー
この記事は役に立ちましたか?