Skip to content

"Expected type [closure@...], found fn pointer" when unnecessarily returning a closure #88097

Closed
@kpreid

Description

@kpreid

Given the following code:

fn peculiar() -> impl Fn(u8) -> u8 {
    return |x| x + 1
}

The current output is:

error[E0308]: mismatched types
 --> src/lib.rs:1:36
  |
1 |   fn peculiar() -> impl Fn(u8) -> u8 {
  |  ____________________________________^
2 | |     return |x| x + 1
3 | | }
  | |_^ expected closure, found fn pointer
  |
  = note:    expected type `[closure@src/lib.rs:2:12: 2:21]`
          found fn pointer `fn(u8) -> u8`

Ideally the code would compile successfully, but if that is infeasible, it would be nice if the diagnostic contained a hint to remove the return. (It's rather head-scratching that the closure is being converted to a fn pointer even though the return type has also been resolved to be the closure type.)

The return is entirely unnecessary here, but I imagine a beginner might include it unthinkingly (as I did) and not be able to even guess that the return has anything to do with the type error.


The results are the same on stable 1.54.0, beta, and nightly.

If I modify the closure to not be coercible to a function pointer by capturing a variable, then the code compiles without error or relevant warning:

fn peculiar(y: u8) -> impl Fn(u8) -> u8 {
    return move |x| x + y
}

Metadata

Metadata

Assignees

Labels

A-closuresArea: Closures (`|…| { … }`)A-diagnosticsArea: Messages for errors, warnings, and lintsA-inferenceArea: Type inferenceT-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