初級 › index out of bounds パニックの原因と直し方 › パターン4
index out of bounds パニックの原因と直し方
存在しない添字でVecや配列にアクセスすると、コンパイルは通りますが実行時にパニックしてプログラムが異常終了します。
1 fn main() { 2 let ages = vec![20, 25, 30]; 3 println!("{}", ages[_]); ^ 4 }
thread 'main' panicked at main.rs:3:24:
index out of bounds: the len is 3 but the index is 6
空欄を埋めて実行を通す
Vecの範囲外アクセスは、C言語のように未定義動作にはならずパニックとして安全に検出されます。
次の問題