首页 > 解决方案 > 字符串的 Rust 期货

问题描述

我一直在尝试理解和使用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它本身?

标签: asynchronousrustasync-awaitrust-tokio

解决方案


当一个函数被声明async时,它隐式地返回一个未来,函数的返回类型作为它的Output类型。所以你会写这个函数:

async fn future_test() -> String {
    "test".to_string()
}

或者,如果您想将返回类型显式指定为 a Future,则可以删除async关键字。如果你这样做了,你还需要构造一个返回的未来,你将无法await在函数内部使用。

fn future_test2() -> impl Future<Output=String> {
    ready("test2".to_string())
}

请注意,它futures::ready构造了一个立即就绪的 Future,这在这种情况下是合适的,因为此函数中没有实际的异步活动。

链接到游乐场


推荐阅读