How can I store function pointers in an array? [duplicate]

At some point recently, each function was given its own, distinct type for… reasons that I don’t recall. Upshot is that you need to give the compiler a hint (note the type on functions):

fn foo() -> isize {
    1
}
fn bar() -> isize {
    2
}
fn main() {
    let functions: Vec<fn() -> isize> = vec![foo, bar];
    println!("foo() = {}, bar() = {}", functions[0](), functions[1]());
}

You can also do this like so:

let functions = vec![foo as fn() -> isize, bar];

Leave a Comment