How to use object objects for function callbacks?

I am trying to wrap my head around target objects and how I can use them. One scenario is that I can pass a function to the callback when some condition called by the callback is fulfilled.

fn bind_callback( key: u64, /* pass function */) {
    // when key is matched with the event, call the function
}

How can i do this? I heard that I can use feature objects for something like this, but how can I implement this? Can someone show me an example? Here is what I find:

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
}

I know this is terribly wrong, I'm trying to figure out how I would do something like that. My error output:

<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 `[closure@<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
+4
source share
2 answers

, . Fn*:

fn pass_callback<F>(f: F)
    where F: Fn()
{
    f();
}

fn run_me() {
    println!("Hello World!");
}

fn main() {
    pass_callback(run_me);
    pass_callback(|| println!("Hello World!"));
}

, , - :

trait Callback {
    fn callback(&self, value: u8) -> bool;
}

struct IsEven;
impl Callback for IsEven {
    fn callback(&self, value: u8) -> bool {
        value % 2 == 0
    }
}

fn pass_callback<C>(f: C)
    where C: Callback
{
    if f.callback(42) {
        println!("Callback passed");
    }
}

fn main() {
    pass_callback(IsEven);
}

,

no arg void ret function

. Rust void ", , .

+6

, , , run_me || println!("Hello World!") . , Callback , Fn():

trait Callback {
    fn callback(&self);
}

fn pass_callback(f: &Callback) {
    f.callback();
}

fn run_me() {
    println!("Hello World!");
}

// For every type T that implements Fn(),
// this is the Callback implementation.
impl<T: Fn()> Callback for T {
    fn callback(&self) {
        self()
    }
}

fn main() {
    pass_callback(&run_me); // a simple function
    pass_callback(&|| println!("Hello World!")); // a closure
}
+2

Source: https://habr.com/ru/post/1629977/


All Articles