字符串的 Rust 期货

Rust Futures for String

我一直在尝试理解和使用 futures(0.3 版),但无法完成这项工作。据我了解,只有当类型 A 实现了未来特征时,函数才能 return 类型为 A 的未来。如果我创建一个结构并实现 future 特征,没关系,但为什么 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 时,它隐含地 return 是一个未来,函数的 return 类型作为其 Output 类型。所以你会写这个函数:

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

或者,如果您想将 return 类型明确指定为 Future,您可以删除 async 关键字。如果你这样做了,你还需要构建 return 的未来,并且你将无法在函数内部使用 await

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

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

Link to Playground