Multi fn items can be casted to fn pointers implicitly but it does not work with only one fn item
Open
Nobody has claimed this yet.
A-coercions
A-diagnostics
T-compiler
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
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
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the shown Vec<fn()> collection with Rust nightly 1.84.0-nightly, then compare it with the two-function version that already succeeds. Trace how the compiler handles function-item types, coercion to function pointers, and Iterator::Item during collect; done means the one-function example compiles successfully and has regression coverage.
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
- Mostly clear
- Newbie friendliness
- 38/100