3
我想註冊Gen::my_g
作爲回調。簡單的方法是實現trait Foo
爲Gen
,但我不想爲Gen
實施trait Foo
。如何使用閉包而不是特質?
換句話說,我想註釋掉標記爲B!!!
的代碼並取消註釋標記爲A!!!
的代碼。
這不是我的代碼;我不能修改這個:
struct S1;
struct TT;
trait MyRes {}
trait Foo {
fn g<'a>(&self, ecx: &'a mut S1, tt: &[TT]) -> Box<MyRes + 'a>;
}
impl<F> Foo for F
where
F: for<'a> Fn(&'a mut S1, &[TT]) -> Box<MyRes + 'a>,
{
fn g<'a>(&self, ecx: &'a mut S1, tt: &[TT]) -> Box<MyRes + 'a> {
(*self)(ecx, tt)
}
}
fn f1<F>(name: &str, extension: F)
where
F: Foo + 'static,
{
}
這是我的代碼:
struct Gen {}
impl Gen {
fn register(self) {
// f1("aaa", move |ecx, tt| self.my_g(ecx, tt));//A!!!
f1("aaa", self); //B!!!
}
fn my_g<'a>(&self, ecx: &'a mut S1, tt: &[TT]) -> Box<MyRes + 'a> {
unimplemented!();
}
}
impl Foo for Gen {
fn g<'a>(&self, ecx: &'a mut S1, tt: &[TT]) -> Box<MyRes + 'a> {
self.my_g(ecx, tt)
}
}
如果我取消//A!!!
,編譯器會告訴我的東西,我不明白:
error[E0271]: type mismatch resolving `for<'a, 'r> <[[email protected]/main.rs:29:19: 29:52 self:_] as std::ops::FnOnce<(&'a mut S1, &'r [TT])>>::Output == std::boxed::Box<MyRes + 'a>`
--> src/main.rs:29:9
|
29 | f1("aaa", move |ecx, tt| self.my_g(ecx, tt)); //A!!!
| ^^ expected bound lifetime parameter, found concrete lifetime
|
= note: concrete lifetime that was found is lifetime '_#12r
= note: required because of the requirements on the impl of `Foo` for `[[email protected]/main.rs:29:19: 29:52 self:_]`
= note: required by `f1`
error[E0281]: type mismatch: `[[email protected]/main.rs:29:19: 29:52 self:_]` implements the trait `std::ops::Fn<(&mut S1, &[TT])>`, but the trait `for<'a, 'r> std::ops::Fn<(&'a mut S1, &'r [TT])>` is required
--> src/main.rs:29:9
|
29 | f1("aaa", move |ecx, tt| self.my_g(ecx, tt)); //A!!!
| ^^ --------------------------------- implements `std::ops::Fn<(&mut S1, &[TT])>`
| |
| requires `for<'a, 'r> std::ops::Fn<(&'a mut S1, &'r [TT])>`
| expected concrete lifetime, found bound lifetime parameter
|
= note: required because of the requirements on the impl of `Foo` for `[[email protected]/main.rs:29:19: 29:52 self:_]`
= note: required by `f1`
的https://stackoverflow.com/q/31362206/2731452 你的情況重複你可以使用'FN constrain_handler(F:F) - > F其中F:爲<'a> FN('一MUT S1, &[TT]) - >方框 {f}' –
red75prime