Skip to content

Confusing mismatched type error (part 2) #48136

Closed
@joshlf

Description

@joshlf

Related to (but different from) #43608.

If you have a function whose return type uses impl trait, you can get confusing type inference errors. The following code...

fn foo() -> impl std::fmt::Debug {
    if false {
        return;
    }
    
    "hello"
}

...produces the following error:

error[E0308]: mismatched types
  --> src/main.rs:12:5
   |
12 |     "hello"
   |     ^^^^^^^ expected (), found reference
   |
   = note: expected type `()`
              found type `&'static str`

In a much more complicated and less obvious instance of this issue, I spent a long time trying to figure out why the compiler thought that impl std::fmt::Debug implied that my return value had to be (). It would be very helpful if the compiler could say something like "expected type () because of this line" and point to the original return (or whatever line caused the inference).

Without impl trait, the issue is less prominent because the types must match exactly, and as a result, if the two different return values have different types, at least one of them must fail to match the stated return type in the function declaration. Consider, for example, the following code:

fn bar() -> &'static str {
    if false {
        return;
    }
    
    "hello"
}

which gives the following error:

error[E0069]: `return;` in a function whose return type is not `()`
  --> src/main.rs:17:9
   |
17 |         return;
   |         ^^^^^^ return type is not ()

The issue with impl trait is that both return values might implement the trait (in this case, both () and &'static str implement Debug), and so you don't get the same useful messages that you would with a concrete return type.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions