知识卡片
函数指针与闭包约束
fn(i32) -> i32 是函数指针类型,可接受签名匹配的命名函数,无法携带捕获的环境。函数指针也实现 Fn、FnMut、FnOnce。若回调接口允许捕获,用泛型和最合适的闭包 trait 就能接受函数和闭包。迭代器 map 也可直接接收签名吻合的 trait 方法或枚举变体构造器。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 高级特性 Dynamically Sized Types and the Sized Trait · 查看原书依据
Function pointers implement all three of the closure traits (Fn, FnMut, and FnOnce), meaning you can always pass a function pointer as an argument for a function that expects a closure. It’s best to write functions using a generic type and one of the closure traits so your functions can accept either functions or closures.
参考来源
- 位置:《The Rust Programming Language(第2版)》第19章 高级特性(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c19.xhtml`,块 0295)
- 结论依据:原文说明 fn 指针同时实现三种闭包 trait,并建议由约束开放两类回调参数。
- 原始内容:Function pointers implement all three of the closure traits (Fn, FnMut, and FnOnce), meaning you can always pass a function pointer as an argument for a function that expects a closure. It’s best to write functions using a generic type and one of the closure traits so your functions can accept either functions or closures.