Skip to content

Detect type parameters that were meant to be impl Trait in return position #78906

@estebank

Description

@estebank

Given fn foo<T: Any>() -> T { "" } the output is:

error[E0308]: mismatched types
 --> src/main.rs:3:5
  |
2 | fn foo<T: Any>() -> T {
  |        -            - expected `T` because of return type
  |        |
  |        this type parameter
3 |     ""
  |     ^^ expected type parameter `T`, found `&str`
  |
  = note: expected type parameter `T`
                  found reference `&'static str`

We should be suggesting the use of impl Trait while explaining that the callers of foo will only be able to access whatever the trait bounds allow: fn foo() -> impl Any { "" }. We should also likely add an additional note for the special case of an Any bound letting people know that it is very unlikely what they want to do.

(Taken from a subset of https://users.rust-lang.org/t/how-can-we-return-a-anonymous-type-in-result-trait/51258)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-impl-traitArea: `impl Trait`. Universally / existentially quantified anonymous types with static dispatch.A-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`A-type-systemArea: Type systemD-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions