Skip to content

Named functions do not implement traits implemented on fn() #121632

Closed
@yvie-k

Description

@yvie-k

I tried this code:

trait Foo {}

impl Foo for fn() {}

fn main() {
    let x: &dyn Foo = &main;
}

playground link

I expected this code to compile, as main is a fn() pointer, which implements the trait Foo

However, rustc seems to need additiontal casting to convert a named fn() to a unnamed one:

   Compiling playground v0.0.1 (/playground)
error[E0277]: the trait bound `fn() {main}: Foo` is not satisfied
 --> src/lib.rs:6:23
  |
6 |     let x: &dyn Foo = &main;
  |                       ^^^^^ the trait `Foo` is not implemented for fn item `fn() {main}`
  |
  = note: required for the cast from `&fn() {main}` to `&dyn Foo`
help: the trait `Foo` is implemented for fn pointer `fn()`, try casting using `as`
  |
6 |     let x: &dyn Foo = &main as fn();
  |                             +++++++

For more information about this error, try `rustc --explain E0277`.
error: could not compile `playground` (lib) due to 1 previous error

On a side note, the solution suggested by rustc is missing parentheses. The correct way would be &(main as fn()). When following the suggestions given by rustc, the code goes &main -> &main as fn() -> &(&main as fn()). The last code suggestion is an invalid cast, because you cannot cast &fn() to fn().

Meta

rustc --version --verbose:

rustc 1.76.0 (07dca489a 2024-02-04)
binary: rustc
commit-hash: 07dca489ac2d933c78d3c5158e3f43beefeb02ce
commit-date: 2024-02-04
host: x86_64-unknown-linux-gnu
release: 1.76.0
LLVM version: 17.0.6

(also happens on beta and nightly)

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsC-bugCategory: This is a bug.D-incorrectDiagnostics: A diagnostic that is giving misleading or incorrect information.D-papercutDiagnostics: An error or lint that needs small tweaks.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions