← 返回刚才阅读的位置

知识卡片

普通读书笔记卡 · 1395.b.3 · 生成模型:未记录

闭包携带执行环境

理解等级:中级

闭包由可调用的代码和所捕获的定义环境组成。|| self.most_stocked() 没有显式参数,仍能借用当前 Inventory。将其传给 Option::unwrap_or_else 后,只有缺少 Some 时才调用,因而可以推迟备用计算。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    参考来源

    - 位置:《The Rust Programming Language(第2版)》第13章 函数式语言特性:迭代器与闭包(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c13.xhtml`,块 0024) - 结论依据:`unwrap_or_else` 能运行使用当前库存的代码,因为闭包携带对 self 的引用。 - 原始内容:One interesting aspect here is that we’ve passed a closure that calls self.most_stocked() on the current Inventory instance. The standard library didn’t need to know anything about the Inventory or ShirtColor types we defined, or the logic we want to use in this scenario. The closure captures an immutable reference to the self Inventory instance and passes it with the code we specify to the unwrap_or_else method.