我想把頭圍繞特質對象,以及如何使用它們。一種情況是我可能想要爲回調傳遞一個函數,當滿足某個條件時會調用回調函數。如何使用trait對象進行函數回調?
fn bind_callback(key: u64, /* pass function */) {
// when key is matched with the event, call the function
}
我該怎麼做?我聽說我可以使用特質對象來實現這個目標,但是我會如何去實現這個目標呢?有人能給我看一個例子嗎?下面是我在什麼:
trait Callback {
fn callback(self);
}
fn pass_callback(f: &Callback) {
f.callback();
}
fn run_me() {
println!("Hello World!");
}
fn main() {
pass_callback(&run_me); // run simple no arg void ret function
pass_callback(|| println!("Hello World!")); // same thing
}
我知道這是極其錯誤的,我想明白,我怎麼會做到這樣的事情。我的錯誤輸出是:
<anon>:14:19: 14:26 error: the trait `Callback` is not implemented for the type `fn() {run_me}` [E0277]
<anon>:14 pass_callback(&run_me);
^~~~~~~
<anon>:14:19: 14:26 help: see the detailed explanation for E0277
<anon>:14:19: 14:26 note: required for the cast to the object type `Callback`
<anon>:15:19: 15:46 error: mismatched types:
expected `&Callback`,
found `[[email protected]<anon>:15:19: 15:46]`
(expected &-ptr,
found closure) [E0308]
<anon>:15 pass_callback(|| println!("Hello World!"));
^~~~~~~~~~~~~~~~~~~~~~~~~~~
<anon>:15:19: 15:46 help: see the detailed explanation for E0308
error: aborting due to 2 previous errors
playpen: application terminated with error code 101