初級 › index out of bounds パニックの原因と直し方 › パターン1
index out of bounds パニックの原因と直し方
存在しない添字でVecや配列にアクセスすると、コンパイルは通りますが実行時にパニックしてプログラムが異常終了します。
1 fn main() { 2 let scores = vec![85, 90, 78]; 3 println!("{}", scores[_]); ^ 4 }
thread 'main' panicked at main.rs:3:26:
index out of bounds: the len is 3 but the index is 5
空欄を埋めて実行を通す
scoresの要素数は3なので、有効な添字は0から2までです。5は範囲外なのでパニックします。
次の問題