知识卡片

普通读书笔记卡 · 6074.f.1.f · 生成模型:未记录

越界可崩溃或返回缺失

理解等级:高级

向量索引从零开始。通过 &v[i] 得到元素引用,i 超出范围会 panic。v.get(i) 提供 Option<&T>,用 Some 或 None 明确处理结果。索引代表程序理应成立的不变量时,可用直接索引;索引来自用户等可能出错的输入时,get 能把错误变成可恢复路径。

相关卡片 [[缺失进入类型系统]]

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • 常用集合 Reading Elements of Vectors · 查看原书依据

      When the get method is passed an index that is outside the vector, it returns None without panicking. You would use this method if accessing an element beyond the range of the vector may happen occasionally under normal circumstances. Your code will then have logic to handle having either Some(&element) or None, as discussed in Chapter 6. For example, the index could be coming from a person entering a number.

    参考来源

    - 位置:《The Rust Programming Language(第2版)》第08章 常用集合(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c08.xhtml`,块 0035) - 结论依据:原文解释 get 越界返回 None,并用用户输入举例说明何时应保留恢复路径。 - 原始内容:When the get method is passed an index that is outside the vector, it returns None without panicking. You would use this method if accessing an element beyond the range of the vector may happen occasionally under normal circumstances. Your code will then have logic to handle having either Some(&element) or None, as discussed in Chapter 6. For example, the index could be coming from a person entering a number.