Skip to content

Confusing error message with reference to boxed trait object #54512

@varkor

Description

@varkor
fn main() {
    let _: Box<dyn '_ + Fn()> = Box::new(|| {});
    let _: &'_ Box<dyn '_ + Fn()> = &Box::new(|| {}); //~ ERROR
}

Results in:

error[E0308]: mismatched types
 --> src/main.rs:3:37
  |
3 |     let _: &'_ Box<dyn '_ + Fn()> = &Box::new(|| {});
  |                                     ^^^^^^^^^^^^^^^^ expected trait std::ops::Fn, found closure
  |
  = note: expected type `&std::boxed::Box<dyn std::ops::Fn()>`
             found type `&std::boxed::Box<[closure@src/main.rs:3:47: 3:52]>`

This error message is confusing, because without the reference the types match up, so it seems odd that there's a type error as soon as a reference is introduced.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-coercionsArea: implicit and explicit `expr as Type` coercionsA-diagnosticsArea: Messages for errors, warnings, and lintsA-dyn-traitArea: trait objects, vtable layoutC-enhancementCategory: An issue proposing an enhancement or a PR with one.D-confusingDiagnostics: Confusing error or lint that should be reworked.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