Skip to content

Cannot coerce closures to fn(...) -> ... in a slice if the slice contains only one function #48109

Closed
@symphorien

Description

@symphorien
fn useful(i: usize) -> usize {
    i
}

fn useful2(i: usize) -> usize {
    i
}

fn main() {
    for f in &[useful, useful2, |x| x] {
        println!("{}", f(6));
    }
}

compiles and runs fine. (see https://play.rust-lang.org/?gist=de9e7ce8fd0683e1dbdcf362a2e16dd4&version=stable)
but if I remove useful2 from the slice, type inference fails:

error[E0308]: mismatched types
  --> src/main.rs:10:24
   |
10 |     for f in &[useful, |x| x] {
   |                        ^^^^^ expected fn item, found closure
   |
   = note: expected type `fn(usize) -> usize {useful}`
              found type `[closure@src/main.rs:10:24: 10:29]`

(see https://play.rust-lang.org/?gist=428522c1c8e14eefaa690d5d09e67b82&version=stable )

If I insert useful twice (ie &[useful, useful, |x| x]) I still get this error.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-closuresArea: Closures (`|…| { … }`)A-coercionsArea: implicit and explicit `expr as Type` coercionsA-type-systemArea: Type systemC-enhancementCategory: An issue proposing an enhancement or a PR with one.T-langRelevant to the language team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions