知识卡片

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

返回闭包的类型表示

理解等级:中级

函数不能直接以裸 dyn Fn(…) -> … 作为按值返回类型,因为特征对象所代表的具体值大小未知。用 Box i32> 让返回的指针大小固定,并通过动态分派调用。所有返回路径使用同一种具体闭包类型时,可用 impl Fn 隐藏编译器知道但源码难以直接表达的类型。

相关卡片 [[动态尺寸类型放在指针后]]、[[静态与动态分派]]

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • 高级特性 Dynamically Sized Types and the Sized Trait · 查看原书依据

      error[E0746]: return type cannot have an unboxed trait object --> src/lib.rs:1:25 | 1 | fn returns_closure() -> dyn Fn(i32) -> i32 { | ^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time | = note: for information on `impl Trait`, see <https://doc.rust-lang.org/book/ch10-02-traits.html#returning-types-that- implement-traits> help: use `impl Fn(i32) -> i32` as the return type, as all return paths are of type `[closure@src/lib.rs:2:5: 2:14]`, which implements `Fn(i32) -> i32` | 1 | fn

    参考来源

    - 位置:《The Rust Programming Language(第2版)》第19章 高级特性(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c19.xhtml`,块 0311) - 结论依据:编译器诊断解释裸特征对象无已知尺寸,并明确给出同一返回类型时的 impl Fn 写法,下一处清单展示 Box。 - 原始内容:error[E0746]: return type cannot have an unboxed trait object --> src/lib.rs:1:25 | 1 | fn returns_closure() -> dyn Fn(i32) -> i32 { | ^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time | = note: for information on `impl Trait`, see <https://doc.rust-lang.org/book/ch10-02-traits.html#returning-types-that- implement-traits> help: use `impl Fn(i32) -> i32` as the return type, as all return paths are of type `[closure@src/lib.rs:2:5: 2:14]`, which implements `Fn(i32) -> i32` | 1 | fn