Search code examples
rustparametersfunction-pointers

How to define a function pointer that returns a value?


I would like to create a callback function. The following code is not working but it shows what I want to do. Here is the link of my broken program in Rust Playground.

fn use_callback(callback: fn()) -> i32 {
    callback()
}

fn callback() -> i32 {
    2
}

fn main() {
    println!("Result: {:?}", use_callback(callback));
}

The expected result should be Result: 2.


Solution

  • You just need to change the type of callback in the use_callback function to a function pointer that returns an i32.

    fn use_callback(callback: fn() -> i32) -> i32 {
                               //  ^^^^^^ here 
        return callback();
    }
    fn callback() -> i32 {
        return 2;
    }
    fn main() {
        println!("Result: {:?}", use_callback(callback));
    }
    

    rust playground