How to define a function pointer that returns a value?

73 Views Asked by At

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.

1

There are 1 best solutions below

0
mandy8055 On BEST ANSWER

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