rust-lang / rust-lang/rust

Closure Fn* trait coercion removes other implementable Fn* traits

Open
#129,381 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-closures A-inference C-bug T-types
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I tried this code:

fn demo<F: FnOnce()>(f: F) -> F { f }

fn other<F: Fn()>(_f: F) {}

fn main() {
    let x = || ();
    other(x); 
    
    let x = demo(|| ());
    other(x); 
}

I expected to see this happen: The code to compile.

Instead, this happened: Compilation failed stating the second x does not implement Fn.

error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce`
  --> src/main.rs:9:18
   |
9  |     let x = demo(|| ());
   |                  ^^ this closure implements `FnOnce`, not `Fn`
10 |     other(x); 
   |     ----- - the requirement to implement `Fn` derives from here
   |     |
   |     required by a bound introduced by this call
   |
note: required by a bound in `other`
  --> src/main.rs:3:13
   |
3  | fn other<F: Fn()>(_f: F) {}
   |             ^^^^ required by this bound in `other`

playground

I would expect this to either compile fine (which means changing something about how closure coercion works) or for the diagnostic given to point at the coercion to a FnOnce for the reason why it doesn't implement the Fn trait.

Meta

rustc --version --verbose:

rustc 1.80.1 (3f5fd8dd4 2024-08-06)
binary: rustc
commit-hash: 3f5fd8dd41153bc5fdca9427e9e05be2c767ba23
commit-date: 2024-08-06
host: x86_64-unknown-linux-gnu
release: 1.80.1
LLVM version: 18.1.7

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.

Research direction

Start with the minimal reproduction in src/main.rs and the linked Rust Playground, then investigate closure FnOnce coercion and the resulting diagnostic. Determine whether the coercion should preserve the other Fn* traits or whether the error should identify the coercion; done means the example compiles or the diagnostic points to that coercion.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.