rust-lang / rust-lang/rust

`impl Fn(T)` argument type is not infered from return type

Open
#138,530 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-impl-trait A-inference C-discussion T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I tried this code:

struct Acceptor<T>(Box<dyn Fn(T)>);

impl<T: 'static> Acceptor<T> {
    fn new(f: impl 'static + Fn(T)) -> Self {
        Self(Box::new(f))
    }

    fn new_fn(f: fn(T)) -> Self {
        Self(Box::new(f))
    }
}

fn test_ok1() -> Acceptor<String> {
    Acceptor(Box::new(|x| {
        println!("{}", x.len());
    }))
}

fn test_ok2() -> Acceptor<String> {
    Acceptor::new_fn(|x| {
        println!("{}", x.len());
    })
}

fn test_ok3() -> Acceptor<String> {
    Acceptor::new(|x| {
        println!("{}", x);
    })
}

fn test_ok4() -> Acceptor<String> {
    Acceptor::<String>::new(|x| {
        println!("{}", x.len());
    })
}

// This is the only one that fails
fn test_fail() -> Acceptor<String> {
    Acceptor::new(|x| {
        println!("{}", x.len());
    })
}

I expected all of the test functions to compile, but the last one fails to infer the type of the variable x.

Error message:

error[E0282]: type annotations needed
  --> src/lib.rs:39:20
   |
39 |     Acceptor::new(|x| {
   |                    ^
40 |         println!("{}", x.len());
   |                        - type must be known at this point
   |
help: consider giving this closure parameter an explicit type
   |
39 |     Acceptor::new(|x: /* Type */| {
   |                     ++++++++++++
Meta

Reproduces on nightly too.

rustc --version --verbose:

rustc 1.85.0 (4d91de4e4 2025-02-17)
binary: rustc
commit-hash: 4d91de4e48198da2e33413efdcd9cd2cc0c46688
commit-date: 2025-02-17
host: x86_64-unknown-linux-gnu
release: 1.85.0
LLVM version: 19.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

Reproduce the failure from the code in src/lib.rs, focusing on test_fail and the contrast with test_ok1 through test_ok4. Trace how closure argument types are inferred from the expected Acceptor return type, then add a regression test and confirm the failing example compiles without explicit parameter annotations.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.