How to Use Enum Variants as Function Pointers

You cannot use enum variants as function pointers; instead, store function pointers inside enum variants and match to call them.

You cannot use enum variants directly as function pointers because they are not functions. Instead, define an enum where each variant holds a function pointer, then match on the enum to call the correct function.

fn add(a: i32, b: i32) -> i32 { a + b }
fn sub(a: i32, b: i32) -> i32 { a - b }

enum Operation {
    Add(fn(i32, i32) -> i32),
    Sub(fn(i32, i32) -> i32),
}

fn main() {
    let op = Operation::Add(add);
    match op {
        Operation::Add(f) => println!("{}", f(2, 3)),
        Operation::Sub(f) => println!("{}", f(2, 3)),
    }
}