【问题标题】:Rust Futures for String字符串的 Rust 期货
【发布时间】: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() -&gt; String
  • @apetranzilla 好的,但是如果我不使用异步怎么办?
  • 我不确定你的意思。异步函数会自动编译为期货,无论它们是否实际使用 await,因此 async fn hello() -&gt; String { "hello".to_string() } 将编译为返回 impl Future&lt;Output=String&gt; 的函数,该函数将在轮询时立即完成。
  • @apetranzilla 我的意思是为什么手动编写它不会编译?
  • 如果要手动编写,需要去掉async限定符。该函数将是fn hell() -&gt; impl Future&lt;Output=String&gt; { /* ... */ }。实现Future 的实际类型将是您必须手动编写或从另一个板条箱导入的东西(如futures);编译器特别支持从 async fns 生成无法手动完全复制的期货。

标签: asynchronous rust async-await rust-tokio


【解决方案1】:

当一个函数被声明为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,这在这种情况下是合适的,因为该函数中没有实际的异步活动。

Link to Playground

【讨论】:

  • 我不必使用生命周期参数,它现在很有意义。谢谢!
猜你喜欢
  • 2020-04-20
  • 1970-01-01
  • 2017-04-10
  • 1970-01-01
  • 1970-01-01
  • 2023-01-11
  • 2020-11-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多