? in async Blocks

就像在async fn?async代码块内的使用很常见。但是,async代码块的返回类型是没有明确说明的。这可能会导致编译器无法推断async代码块的 error 类型。

例如,此代码:

  1. let fut = async {
  2. foo().await?;
  3. bar().await?;
  4. Ok(())
  5. };

将触发此错误:

  1. error[E0282]: type annotations needed
  2. --> src/main.rs:5:9
  3. |
  4. 4 | let fut = async {
  5. | --- consider giving `fut` a type
  6. 5 | foo().await?;
  7. | ^^^^^^^^^^^^ cannot infer type

不幸的是,目前没有办法“giving fut a type”(给fut一个类型),解决的办法也不是明确指定async代码块的返回类型。

要解决此问题,请使用“turbofish”操作符,为async代码块提供成功和错误类型。:

  1. let fut = async {
  2. foo().await?;
  3. bar().await?;
  4. Ok::<(), MyError>(()) // <- 注意这里的明确类型声明
  5. };