知识卡片

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

按调用方式约束回调

理解等级:高级

回调调用次数与状态需求决定 trait bound。备用值最多计算一次,接受 FnOnce 可兼容消耗环境的闭包。排序键会多次计算,接受 FnMut 可以用计数器跟踪调用,但闭包必须保留供下一次使用的捕获值。普通函数项也能作回调。

相关卡片 [[闭包调用约束的三层]]

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    参考来源

    - 位置:《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.