Return Type Errors

在典型的 Rust 函数中,返回的值若是有个错误的类型,将导致出现如下所示的错误:

  1. error[E0308]: mismatched types
  2. --> src/main.rs:2:12
  3. |
  4. 1 | fn foo() {
  5. | - expected `()` because of default return type
  6. 2 | return "foo"
  7. | ^^^^^ expected (), found reference
  8. |
  9. = note: expected type `()`
  10. found type `&'static str`

但是,目前async fn的支持,还不知道“信任”函数签名中编写的返回类型,从而导致不匹配甚至反标准错误。例如,函数async fn foo() { "foo" }导致此错误:

  1. error[E0271]: type mismatch resolving `<impl std::future::Future as std::future::Future>::Output == ()`
  2. --> src/lib.rs:1:16
  3. |
  4. 1 | async fn foo() {
  5. | ^ expected &str, found ()
  6. |
  7. = note: expected type `&str`
  8. found type `()`
  9. = note: the return type of a function must have a statically known size

这个错误说得是:它 expected &str,但发现了(),实际上,这就与您想要的完全相反。这是因为编译器错误地信任,函数主体会返回正确的类型。

此问题的变通办法是识别,指向带有”expected SomeType, found OtherType“信息的函数签名的错误,通常表示一个或多个返回站点不正确。

Fix in this bug,可以跟踪浏览下。

Box<dyn Trait>

同样,由于函数签名的返回类型,没有正确传播,因此来自async fn的值,没有正确地强制使用其预期的类型。

实践中,这意味着,async fn返回的Box<dyn Trait>对象需要手动as,将Box<MyType>转为Box<dyn Trait>

此代码将导致错误:

  1. async fn x() -> Box<dyn std::fmt::Display> {
  2. Box::new("foo")
  3. }

可以通过使用as,这个错误就消除了:

  1. async fn x() -> Box<dyn std::fmt::Display> {
  2. Box::new("foo") as Box<dyn std::fmt::Display>
  3. }

Fix in this bug,可以跟踪浏览。