Skip to content

Error message for type mismatch between impl Traits needs better explanation #57266

Closed
@kornelski

Description

@kornelski

The message "expected type impl Trait (opaque type), found type impl Trait (opaque type)" sounds like a paradox: the compiler has found exactly what it expected, and yet it doesn't match.

The explanatory text of E0308 is the same as for all other banal type errors, so it's not addressing this problem specifically.

From the questions I'm seeing in the user forum I have an impression that users think impl Trait is like dyn Trait and try to use it as an abstraction for mixing different types.

fn f1() -> impl Copy {
    "1"
}
fn f2() -> impl Copy {
    2
}

fn main() {
    let mut x = f1();
    x = f2();
}

10 | x = f2();
| ^^^^ expected opaque type, found a different opaque type
|
= note: expected type impl std::marker::Copy (opaque type)
found type impl std::marker::Copy (opaque type)


Suggestions:

  • Make it a separate error, so that it'll get its own rustc --explain document.

  • If possible, instead of "(opaque type)" print more internal type information, e.g. like for closures:

    = note: expected type `impl [std::marker::Copy@src/main.rs:2:10]`
            found type `impl [std::marker::Copy@src/main.rs:5:10]`
    
    = note: each `impl Trait`, even for the same trait, is a different type.
    = help: consider using `Box<dyn Trait>` or separate generic parameters.
    

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 systemT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions