第 21 课2026.09.28
用上节课找到的索引读取分数,同时处理索引越界。
第 21 课:安全读取匹配位置的元素
- 日期:2026-09-28
- 课程序号:第 21 课
- 知识点:切片
get()
用途或适用场景
用上节课找到的索引读取分数,同时处理索引越界。
核心概念
scores.get(index) 返回 Option<&i32>:有效位置得到借用值,越界得到 None,不会因索引访问而 panic。
最小代码或操作示例
rust
fn main() {
let scores = [3, 8, 5, 8];
let last = scores.iter().rposition(|value| *value == 8);
if let Some(index) = last {
assert_eq!(scores.get(index), Some(&8));
}
assert_eq!(scores.get(99), None);
}3~5 分钟练习
把目标分数改为 5,断言最后一次匹配位置及读取结果。
参考答案
rust
let index = scores.iter().rposition(|value| *value == 5);
assert_eq!(index, Some(2));
assert_eq!(scores.get(2), Some(&5));与上一课的联系
沿用第 20 课的 scores 与 rposition 结果;本课只新增 get() 按索引安全读取;下一课可把匹配位置与读取出的值组合成一条结果。
时效校验
时效校验:2026-09-28(已打开 Rust 当前标准库 slice::get 与 Iterator::rposition 文档;前者自 1.0.0 可用,未见废弃标记)。