我想要:对于一个特征,例如Foo,任何都fn(T1,T2)->()应该实现它,并且我不关心T1或T2是否是引用。
trait Foo {
fn hello_world(&self) -> String {
"hello world".into()
}
}
impl<T1, T2> Foo for fn(T1, T2) -> () {}
fn a_dummy_sample_function(_: i32, _:i32) {}
fn main() {
let fn_ptr : fn(i32, i32)->() = a_dummy_sample_function;
(fn_ptr).hello_world();
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,效果很好。
如果我将第一个参数的类型更改&i32为
trait Foo {
fn hello_world(&self) -> String {
"hello world".into()
}
}
impl<T1, T2> Foo for fn(T1, T2) -> () {}
fn foo_imp(_: &i32, _:i32) {}
fn main() {
let fn_ptr : fn(&i32, i32)->() = foo_imp;
fn_ptr.hello_world();
}
Run Code Online (Sandbox Code Playgroud)
然后,我遇到了以下编译错误。
--> src/main.rs:12:12
|
12 | fn_ptr.hello_world();
| ^^^^^^^^^^^ method not found in `for<'r> fn(&'r i32, i32)`
|
= note: `fn_ptr` is a function, perhaps you wish to call it
= help: items from traits can only be used if the trait is implemented and in scope
note: `Foo` defines an item `hello_world`, perhaps you need to implement it
Run Code Online (Sandbox Code Playgroud)
我可以修复编译错误,如下所示
impl<T1, T2> Foo for for<'a> fn(&'a T1, T2) -> () {}
Run Code Online (Sandbox Code Playgroud)
但这不是我想要的,我想要任何带有任何类型的两个参数的函数指针,无论它是否是引用。
| 归档时间: |
|
| 查看次数: |
431 次 |
| 最近记录: |