如何使特征中的异步函数返回发送的未来?

问题描述 投票:0回答:1

我有一个这样定义的特质:

trait MyTrait {
    async fn my_async_fn(arg: SendType) -> Result<Self, Box<dyn Error>>;
}

如何使 my_async_fn 返回的 future 发送给实现该特征的所有内容?

asynchronous rust traits send rust-tokio
1个回答
0
投票

如果您将特征公开,编译器将帮助您:

warning: use of `async fn` in public traits is discouraged as auto trait bounds cannot be specified
 --> src\main.rs:6:5
  |
6 |     async fn my_async_fn(arg: SendType) -> Result<Self, Box<dyn Error>>;
  |     ^^^^^
  |
  = note: you can suppress this lint if you plan to use the trait only in your own code, or do not care about auto traits like `Send` on the `Future`
  = note: `#[warn(async_fn_in_trait)]` on by default
help: you can alternatively desugar to a normal `fn` that returns `impl Future` and add any desired bounds such as `Send`, but these cannot be relaxed without a breaking API change
  |
6 -     async fn my_async_fn(arg: SendType) -> Result<Self, Box<dyn Error>>;
6 +     fn my_async_fn(arg: SendType) -> impl std::future::Future<Output = Result<Self, Box<dyn Error>>> + Send;

所以:

fn my_async_fn(
    arg: SendType,
) -> impl std::future::Future<Output = Result<Self, Box<dyn Error>>> + Send;
© www.soinside.com 2019 - 2024. All rights reserved.