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 对象” 部分。
接下来让我们学习宏!

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值