0
点赞
收藏
分享

微信扫一扫

rust 返回闭包

闭包表现为 trait,这意味着不能直接返回闭包。对于大部分需要返回 trait 的情况,可以使用实现了期望

返回的 trait 的具体类型来替代函数的返回值。但是这不能用于闭包,因为他们没有一个可返回的具体类

型;例如不允许使用函数指针 fn 作为返回值类型。

这段代码尝试直接返回闭包,它并不能编译:

fn returns_closure() -> dyn Fn(i32) -> i32 {

|x| x + 1

}

编译器给出的错误是:

$ cargo build

Compiling functions-example v0.1.0 (file:///projects/functions-example)

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 returns_closure() -> impl Fn(i32) -> i32 {

| ~~~~~~~~~~~~~~~~~~~

For more information about this error, try `rustc --explain E0746`.

error: could not compile `functions-example` due to previous error

512 CHAPTER 19. 高级特征

错误又一次指向了 Sized trait!Rust 并不知道需要多少空间来储存闭包。不过我们在上一部分见过这种

情况的解决办法:可以使用 trait 对象:

fn returns_closure() -> Box<dyn Fn(i32) -> i32> {

Box::new(|x| x + 1)

}

这段代码正好可以编译。关于 trait 对象的更多内容,请回顾第十七章的 ” 为使用不同类型的值而设计的

trait 对象” 部分。

接下来让我们学习宏!

举报

相关推荐

0 条评论