I am trying to make a trait usable on top-level functions in Rust.
trait FnTrait {
fn call(self);
}
impl FnTrait for fn() {
fn call(self) {
self()
}
}
fn foo() {
println!("Hello, World!")
}
fn main() {
FnTrait::call(foo)
}
However the code below fails to compile with (Playground Link)
error[E0277]: the trait bound `fn() {foo}: FnTrait` is not satisfied
--> <anon>:16:5
|
16 | FnTrait::call(foo)
| ^^^^^^^^^^^^^ the trait `FnTrait` is not implemented for `fn() {foo}`
|
= help: the following implementations were found:
<fn() as FnTrait>
= note: required by `FnTrait::call`
I found I can trick it into compiling by casting foo like so
FnTrait::call(foo as fn())
But it is annoying and some of the functions in my program are more complicated than foo. Any way to avoid the cast? Is my trait wrong somehow?