Skip to content

Multi fn items can be casted to fn pointers implicitly but it does not work with only one fn item #133172

Open
@mu001999

Description

@mu001999

Code

fn foo() {}

fn bar() {}

fn main() {
    let _x: Vec<fn()> = [foo].into_iter().collect();
    // let _x: Vec<fn()> = [foo, bar].into_iter().collect();
}

Current output

error[E0277]: a value of type `Vec<fn()>` cannot be built from an iterator over elements of type `fn() {foo}`
    --> src/main.rs:6:43
     |
6    |     let _x: Vec<fn()> = [foo].into_iter().collect();
     |                                           ^^^^^^^ value of type `Vec<fn()>` cannot be built from `std::iter::Iterator<Item=fn() {foo}>`
     |
     = help: the trait `FromIterator<fn() {foo}>` is not implemented for `Vec<fn()>`
             but trait `FromIterator<fn()>` is implemented for it
     = help: for that trait implementation, expected `fn()`, found `fn() {foo}`
note: the method call chain might not have had the expected associated types
    --> src/main.rs:6:31
     |
6    |     let _x: Vec<fn()> = [foo].into_iter().collect();
     |                         ----- ^^^^^^^^^^^ `Iterator::Item` is `fn() {foo}` here
     |                         |
     |                         this expression has type `[fn() {foo}; 1]`
note: required by a bound in `collect`
    --> /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:1967:19
     |
1967 |     fn collect<B: FromIterator<Self::Item>>(self) -> B
     |                   ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `Iterator::collect`

For more information about this error, try `rustc --explain E0277`.

Desired output

Compiled successfully

Rationale and extra context

The following call with two fn items would be compiled successfully:

fn foo() {}

fn bar() {}

fn main() {
    // let _x: Vec<fn()> = [foo].into_iter().collect();
    let _x: Vec<fn()> = [foo, bar].into_iter().collect();
}

Other cases

Rust Version

Build using the Nightly version: 1.84.0-nightly

(2024-11-17 5ec7d6eee7e0f5236ec1)

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-coercionsArea: implicit and explicit `expr as Type` coercionsA-diagnosticsArea: Messages for errors, warnings, and lintsT-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