知识卡片
标识符模式创建新绑定
外层已有 y = 10 时,普通绑定模式 Some(y) 会匹配所有 Some,并把内部值绑定给新的局部 y。匹配 Some(5) 时分支内的 y 是 5,离开分支后回到外层的 10。想比较旧 y,则用 Some(n) if n == y,让新绑定使用独立名字。if let 中成功解构后的新绑定也有自己的分支作用域。
相关卡片 [[匹配守卫的判定边界]]
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 模式与匹配 Pattern Syntax · 查看原书依据
The pattern in the second match arm ❹ introduces a new variable named y that will match any value inside a Some value. Because we’re in a new scope inside the match expression, this is a new y variable, not the y we declared at the beginning with the value 10 ❷. This new y binding will match any value inside a Some, which is what we have in x.
参考来源
- 位置:《The Rust Programming Language(第2版)》第18章 模式与匹配(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c18.xhtml`,块 0107)
- 结论依据:原文列出外部 y 为 10 而分支中的 y 匹配绑定到 5 的解析过程。
- 原始内容:The pattern in the second match arm ❹ introduces a new variable named y that will match any value inside a Some value. Because we’re in a new scope inside the match expression, this is a new y variable, not the y we declared at the beginning with the value 10 ❷. This new y binding will match any value inside a Some, which is what we have in x.