← 返回刚才阅读的位置

知识卡片

普通读书笔记卡 · 10644.h · 生成模型:未记录

模式何时允许匹配失败

理解等级:中级

对给定类型始终匹配的模式称为不可反驳模式,例如单一变量名。Some(x) 在匹配 Option 时可能遇到 None,因此可反驳。普通 let、for 和参数位置缺少针对失败的控制流,要求不可反驳模式。if let 和 while let 有失败路径,可接收 Some(x);若传入总匹配的模式,则通常会得到无条件匹配的告警。

相关卡片 [[按数据形状选择控制流]]、[[匹配先后与穷尽检查]]

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • 模式与匹配 for Loops · 查看原书依据

      Function parameters, let statements, and for loops can only accept irrefutable patterns because the program cannot do anything meaningful when values don’t match. The if let and while let expressions accept refutable and irrefutable patterns, but the compiler warns against irrefutable patterns because, by definition, they’re intended to handle possible failure: the functionality of a conditional is in its ability to perform differently depending on success or failure.

    参考来源

    - 位置:《The Rust Programming Language(第2版)》第18章 模式与匹配(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c18.xhtml`,块 0076) - 结论依据:原文按控制流能否处理不匹配,区分 let、for、参数与 if let、while let。 - 原始内容:Function parameters, let statements, and for loops can only accept irrefutable patterns because the program cannot do anything meaningful when values don’t match. The if let and while let expressions accept refutable and irrefutable patterns, but the compiler warns against irrefutable patterns because, by definition, they’re intended to handle possible failure: the functionality of a conditional is in its ability to perform differently depending on success or failure.