Skip to content

casting trait methods to FnOnce(&mut dyn Trait) is not ergonomic #68589

@programmerjake

Description

@programmerjake

In the following code, I'm trying to cast Trait::f to FnOnce(&mut dyn Trait) which should be possible, but the obvious method doesn't work. None of the combinations I tried got it to work (I could just use a lambda that called f, but that defeats the purpose).

trait Trait {
    fn f(&mut self);
}

fn g<F: FnOnce(&mut dyn Trait)>(f: F) {}

fn f() {
    g(Trait::f)
}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error[E0631]: type mismatch in function arguments
 --> src/lib.rs:8:7
  |
2 |     fn f(&mut self);
  |     ---------------- found signature of `for<'r> fn(&'r mut _) -> _`
...
5 | fn g<F: FnOnce(&mut dyn Trait)>(f: F) {}
  |    -    ---------------------- required by this bound in `g`
...
8 |     g(Trait::f)
  |       ^^^^^^^^ expected signature of `for<'r> fn(&'r mut (dyn Trait + 'r)) -> _`

error[E0271]: type mismatch resolving `for<'r> <for<'s> fn(&'s mut _) {<_ as Trait>::f} as std::ops::FnOnce<(&'r mut (dyn Trait + 'r),)>>::Output == ()`
 --> src/lib.rs:8:5
  |
5 | fn g<F: FnOnce(&mut dyn Trait)>(f: F) {}
  |    -    ---------------------- required by this bound in `g`
...
8 |     g(Trait::f)
  |     ^ expected bound lifetime parameter, found concrete lifetime

error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0271`.
error: could not compile `playground`.

To learn more, run the command again with --verbose.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.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