知识卡片
按需求值构造缺省项
Option::unwrap_or(default) 的参数在调用前已求值,即使现有选项是 Some。如果构造默认项要额外创建令牌流,可把动作交给 unwrap_or_else(|| ...),只有 None 时闭包体才执行。按需求值也使没有有限结束位置的序列可以分批生成。对于便宜且无副作用的默认值,直接求值通常也清楚。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Builder with attributes 键值写法和惰性回退 · 查看原书依据
Eager and lazy evaluations are two approaches to writing code. Eager evaluation means the code you write will be invoked when it is encountered. Lazy evaluation means that evaluation is postponed until it proves necessary. In listing 8.10, unwrap_or_else is lazy because the closure that creates the default TokenStream will only be called if we end up in the unwrap_or_else call.
参考来源
- 位置:《Write Powerful Rust Macros》第08章《Builder with attributes》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-8.xhtml#p60)
- 结论依据:清单 8.10 用 unwrap_or_else 生成默认令牌,这段原文通过 unwrap_or 的参数求值顺序解释差异。
- 原始内容:Eager and lazy evaluations are two approaches to writing code. Eager evaluation means the code you write will be invoked when it is encountered. Lazy evaluation means that evaluation is postponed until it proves necessary. In listing 8.10, unwrap_or_else is lazy because the closure that creates the default TokenStream will only be called if we end up in the unwrap_or_else call.