初級 › index out of bounds パニックの原因と直し方 › パターン2
index out of bounds パニックの原因と直し方
存在しない添字でVecや配列にアクセスすると、コンパイルは通りますが実行時にパニックしてプログラムが異常終了します。
1 fn main() { 2 let prices = vec![100, 250, 300]; 3 println!("{}", prices[__]); ^ 4 }
thread 'main' panicked at main.rs:3:26:
index out of bounds: the len is 3 but the index is 10
空欄を埋めて実行を通す
添字が変数や計算結果の場合、コンパイラは範囲を事前にチェックできません。範囲外アクセスは実行時にしか分かりません。
次の問題