HashMap Function Table Dispatch
Store fn pointers in a HashMap and dispatch commands by name, handling unknown operations through the Option returned by get.
Code
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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- How do you run HashMap Function Table Dispatch?
- The runtime alone is enough: execute the file as a complete program.
Report a problem with this exampleOpens a pre-filled issue on GitHub.