我一直在尝试理解和使用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本身呢?
发布于 2020-07-19 08:07:44
当一个函数被声明为async时,它隐式返回一个future,函数的返回类型作为它的Output类型。因此,您可以编写以下函数:
async fn future_test() -> String {
"test".to_string()
}或者,如果您希望显式地将返回类型指定为Future,则可以删除async关键字。如果你这样做了,你还需要构造一个返回的未来,并且你将不能在函数中使用await。
fn future_test2() -> impl Future<Output=String> {
ready("test2".to_string())
}请注意,futures::ready构造了一个立即就绪的Future,这在本例中是合适的,因为此函数中没有实际的异步活动。
https://stackoverflow.com/questions/62972822
复制相似问题