知识卡片
匹配先后与穷尽检查
match 要处理输入类型的全部可能,但每次只执行第一个满足条件的分支。对于 Option,把 Some 和 None 都写出即可穷尽,也可用 _ 接住前面的余项。先写宽泛的分支会让后面的具体分支没有机会匹配。多个分支均可处理某个输入时,顺序就是优先级。
相关卡片 [[匹配守卫的判定边界]]
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 模式与匹配 All the Places Patterns Can Be Used · 查看原书依据
One requirement for match expressions is that they need to be exhaustive in the sense that all possibilities for the value in the match expression must be accounted for. One way to ensure you’ve covered every possibility is to have a catch-all pattern for the last arm: for example, a variable name matching any value can never fail and thus covers every remaining case.
参考来源
- 位置:《The Rust Programming Language(第2版)》第18章 模式与匹配(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c18.xhtml`,块 0020)
- 结论依据:原文要求 match 覆盖所有可能,并解释为什么最后一个兜底分支可以处理余项。
- 原始内容:One requirement for match expressions is that they need to be exhaustive in the sense that all possibilities for the value in the match expression must be accounted for. One way to ensure you’ve covered every possibility is to have a catch-all pattern for the last arm: for example, a variable name matching any value can never fail and thus covers every remaining case.