症状
程序 panic,信息形如 index out of bounds: the len is N but the index is M。常出现在被 happy path 假定足够长的短输入或畸形输入上。
诊断
读取 panic 中的长度、下标与出错表达式:
let parts: Vec<_> = line.split(',').collect();
let name = &parts[2]; // panics when fewer than 3 fields
加上长度检查以确认集合比预期更短。
修复
使用不会 panic 的访问器与迭代器:
let name = parts.get(2).ok_or("missing field")?;
for (i, item) in items.iter().enumerate() {
if i > 0 { /* safe: i < len */ }
}
在做区间切片前校验长度。
验证
把原先失败的输入写成测试,断言 parts.get(2) 为 None 而非 panic;解析器应返回清晰错误,且不再发生越界 panic。