初級 › index out of range パニックの原因と直し方 › パターン3
index out of range パニックの原因と直し方
存在しない添字でスライスや配列にアクセスすると、コンパイルは通りますが実行時にパニックしてプログラムが異常終了します。
1 package main 2 3 import "fmt" 4 5 func main() { 6 nums := []int{1, 2, 3, 4, 5} 7 fmt.Println(nums[__]) ^ 8 }
panic: runtime error: index out of range [10] with length 5length 5
空欄を埋めて実行を通す
要素数5のスライスに10番目を指定しても存在しないため、実行時にパニックします。
次の問題