rust-lang / rust-lang/rust

Suggest `impl Fn()` in return type when trying to return a closure coerced to `fn()` pointer

Open
#159,481 2 comments 0 reactions 1 assignee View on GitHub

@DAstapov is already working on this.

Since Jul 20, 2026.

A-closures A-diagnostics A-impl-trait A-suggestion-diagnostics D-lack-of-suggestion D-newcomer-roadblock T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

Code
fn offsetter(offset: i32) -> fn(i32) -> i32 { // should have been `impl Fn(i32) -> i32`.
    |value| value + offset
    //~^ ERROR mismatched types
}

fn main() {}
Current output
error[E0308]: mismatched types
 --> src/main.rs:2:5
  |
1 | fn offsetter(offset: i32) -> fn(i32) -> i32 { // `impl Fn(i32) -> i32`.
  |                              -------------- expected `fn(i32) -> i32` because of return type
2 |     |value| value + offset
  |     ^^^^^^^^^^^^^^^^^^^^^^ expected fn pointer, found closure
  |
  = note: expected fn pointer `fn(i32) -> i32`
                found closure `{closure@src/main.rs:2:5: 2:12}`
note: closures can only be coerced to `fn` types if they do not capture any variables
 --> src/main.rs:2:21
  |
2 |     |value| value + offset
  |                     ^^^^^^ `offset` captured here
Desired output
error[E0308]: mismatched types
 --> src/main.rs:2:5
  |
1 | fn offsetter(offset: i32) -> fn(i32) -> i32 { // `impl Fn(i32) -> i32`.
  |                              -------------- expected `fn(i32) -> i32` because of return type
2 |     |value| value + offset
  |     ^^^^^^^^^^^^^^^^^^^^^^ expected fn pointer, found closure
  |
  = note: expected fn pointer `fn(i32) -> i32`
                found closure `{closure@src/main.rs:2:5: 2:12}`
note: closures can only be coerced to `fn` types if they do not capture any variables
 --> src/main.rs:2:21
  |
2 |     |value| value + offset
  |                     ^^^^^^ `offset` captured here
help: change the return type to return a type-erased closure instead
  |
1 - fn offsetter(offset: i32) -> fn(i32) -> i32 { // `impl Fn(i32) -> i32`.
1 + fn offsetter(offset: i32) -> impl Fn(i32) -> i32 { // `impl Fn(i32) -> i32`.
  |
Rationale and extra context

The distinction is not necessarily easy to understand for newcomers to the language.

Other cases

Rust Version
1.97
Anything else?

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.