Skip to content

Confusing error "expected type parameter, found closure" #51154

Closed
@oberien

Description

@oberien

Minimal example:

fn test<F: FnMut()>() {
    let f: Box<F> = Box::new(|| ());
}

error[E0308]: mismatched types
 --> src/main.rs:2:30
  |
2 |     let f: Box<F> = Box::new(|| ());
  |                              ^^^^^ expected type parameter, found closure
  |
  = note: expected type `F`
             found type `[closure@src/main.rs:2:30: 2:35]`

The error is technically correct. I specified, that I want a box of F, but I create a closure. Because F is generic, it is caller-chosen and I create a new closure, which has a different type.

Still, it took me quite some time to find out what was going on in the more complicated real code. I think that it would help to add a note here explaining, that each closure has a different type, and that the inner closure does not match the type F exactly. Maybe additionally a hint could be added, stating to use Box<FnMut()> instead (i.e. the traits F is bound to).

Metadata

Metadata

Assignees

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.D-papercutDiagnostics: An error or lint that needs small tweaks.T-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