Skip to content

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

Open
@LHolten

Description

@LHolten

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-impl-traitArea: `impl Trait`. Universally / existentially quantified anonymous types with static dispatch.A-inferenceArea: Type inferenceC-discussionCategory: Discussion or questions that doesn't represent real issues.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