知识卡片
按调用方式约束回调
回调调用次数与状态需求决定 trait bound。备用值最多计算一次,接受 FnOnce 可兼容消耗环境的闭包。排序键会多次计算,接受 FnMut 可以用计数器跟踪调用,但闭包必须保留供下一次使用的捕获值。普通函数项也能作回调。
相关卡片 [[闭包调用约束的三层]]
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 函数式语言特性:迭代器与闭包 Moving Captured Values Out of Closures and the Fn Traits · 查看原书依据
The trait bound specified on the generic type F is FnOnce() -> T, which means F must be able to be called once, take no arguments, and return a T. Using FnOnce in the trait bound expresses the constraint that unwrap_or_else is only going to call f one time, at most. In the body of unwrap_or_else, we can see that if the Option is Some, f won’t be called.
参考来源
- 位置:《The Rust Programming Language(第2版)》第13章 函数式语言特性:迭代器与闭包(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c13.xhtml`,块 0075)
- 结论依据:以备用函数最多运行一次为例,说明选择较宽 trait 约束提高适用性。
- 原始内容:The trait bound specified on the generic type F is FnOnce() -> T, which means F must be able to be called once, take no arguments, and return a T. Using FnOnce in the trait bound expresses the constraint that unwrap_or_else is only going to call f one time, at most. In the body of unwrap_or_else, we can see that if the Option is Some, f won’t be called.