HashMap Function Table Dispatch

Store fn pointers in a HashMap and dispatch commands by name, handling unknown operations through the Option returned by get.

RustCli Tooling

Code

rustsnippet
28 lines
use std::collections::HashMap;

fn double(n: i32) -> i32 {
    n * 2
}

fn square(n: i32) -> i32 {
    n * n
}

fn negate(n: i32) -> i32 {
    -n
}

fn main() {
    // function table: fn pointers keyed by name, dispatch via match on get
    let mut ops: HashMap<&str, fn(i32) -> i32> = HashMap::new();
    ops.insert("double", double);
    ops.insert("square", square);
    ops.insert("negate", negate);

    for (name, input) in [("double", 7), ("square", 9), ("negate", 4), ("hex", 1)] {
        match ops.get(name) {
            Some(op) => println!("{name}({input}) = {}", op(input)),
            None => println!("{name}: unknown operation"),
        }
    }
}

Inside the snippet

Structurally, expect the functions double, square, negate and main and nothing else.

A single loop drives the file — for (name, input) in [("double", 7), ("square", 9), ("negate", 4), ("hex", 1)]. A match spells out every case; omit one and the code does not compile.

What to watch for

  • The standard library is the whole story here — nothing to install at all.

Using it

The main signature is written as fn double(n: i32) -> i32

Key statements

fn double(n: i32) -> i32 {
    n * 2
}
fn square(n: i32) -> i32 {
    n * n
}
fn negate(n: i32) -> i32 {
    -n
}

Interactive Tools for This Topic

FAQ

How do you run HashMap Function Table Dispatch?
The runtime alone is enough: execute the file as a complete program.