Skip to content

Suggest Box::new on E0308 when appropriate #63506

Closed
@estebank

Description

@estebank

When encountering a boxed value as expected and a stack allocated value that could be boxed to fulfill the expectation, like in the following snippet, suggest Box::new wrapping:

fn main() {
    let x: Box<Fn() -> _> = || {
        Err(())?;
        Ok(())
    };
}
error[E0308]: mismatched types
 --> src/main.rs:3:29
  |
3 |       let x: Box<Fn() -> _> = || {
  |  _____________________________^
4 | |         Err(())?;
5 | |         Ok(())
6 | |     };
  | |_____^ expected struct `std::boxed::Box`, found closure
  |
  = note: expected type `std::boxed::Box<dyn std::ops::Fn() -> _>`
             found type `[closure@src/main.rs:3:29: 6:6]`

Should suggest:

fn main() {
    let x: Box<Fn() -> _> = Box::new(|| {
        Err(())?;
        Ok(())
    });
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-closuresArea: Closures (`|…| { … }`)A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`C-enhancementCategory: An issue proposing an enhancement or a PR with one.P-lowLow priorityT-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