rustdependenciesfunction-pointers

Passing function pointer from one struct to another without adding dependency


I have two structs Foo and Bar, i want to store function callback of one struct (Foo) in the other (Bar), so that they don't know about each other. Is it possible in rust without Bar knowing that Foo exists (i'm concerned about the dependencies)? Here's c++ sample of what i'm looking for

#include <cstdio>
#include <functional>

struct Foo {
    void test() {
        puts("Test");
    }
};

// bar is in another module which shouldn't depend on Foo
// bar doesn't know about foo
template <typename CallbackT>
struct Bar {
    Bar(CallbackT callback) :
      callback{callback} 
    {}

    void test() {
        puts("Doing some stuff...");
        callback();
    }
    CallbackT callback;
};

int main(int argc, const char* argv[]) {
    Foo foo;
    Bar bar{[&foo]() {
        foo.test();
    }};
    bar.test();
}

Solution

  • Yes, you can do this in Rust. It works and almost looks the same:

    struct Foo {}
    
    impl Foo {
        fn test(&self) {
            println!("Test");
        }
    }
    
    struct Bar<CallbackT> {
        callback: CallbackT,
    }
    
    impl<CallbackT> Bar<CallbackT> {
        fn new(callback: CallbackT) -> Self {
            Bar { callback }
        }
        
        fn test(&self) where CallbackT: Fn() {
            println!("Doing some stuff...");
            (self.callback)();
        }
    }
    
    fn main() {
        let foo = Foo {};
        let bar = Bar::new(|| {
            foo.test()
        });
        bar.test();
    }