【发布时间】:2020-07-19 08:07:44
【问题描述】:
我一直在尝试理解和使用futures(0.3 版),但无法完成这项工作。据我了解,只有A 类型实现了未来特征,函数才能返回A 类型的未来。如果我创建一个结构并实现未来的特征,那没关系,但为什么String 不起作用?
use futures::prelude::*;
async fn future_test() -> impl Future<Output=String> {
return "test".to_string();
}
我得到错误:
the trait bound `std::string::String: core::future::future::Future` is not satisfied
the trait `core::future::future::Future` is not implemented for `std::string::String`
note: the return type of a function must have a statically known sizerustc(E0277)
所以我告诉自己,好吧,那么我可以使用Box 喜欢:
async fn future_test() -> impl Future<Output=Box<String>> {
return Box::new("test".to_string());
}
但错误是一样的:
the trait bound `std::string::String: core::future::future::Future` is not satisfied
the trait `core::future::future::Future` is not implemented for `std::string::String`
note: the return type of a function must have a statically known sizerustc(E0277)
我做错了什么?为什么未来会持有String 而不是Box 本身?
【问题讨论】:
-
async fn会自动为您包装返回类型,因此您应该将签名更改为async fn future_test() -> String。 -
@apetranzilla 好的,但是如果我不使用异步怎么办?
-
我不确定你的意思。异步函数会自动编译为期货,无论它们是否实际使用 await,因此
async fn hello() -> String { "hello".to_string() }将编译为返回impl Future<Output=String>的函数,该函数将在轮询时立即完成。 -
@apetranzilla 我的意思是为什么手动编写它不会编译?
-
如果要手动编写,需要去掉
async限定符。该函数将是fn hell() -> impl Future<Output=String> { /* ... */ }。实现Future的实际类型将是您必须手动编写或从另一个板条箱导入的东西(如futures);编译器特别支持从async fns 生成无法手动完全复制的期货。
标签: asynchronous rust async-await rust-tokio