Map Function Tables Dispatch Commands
Register subcommands in a map[string]func table so new commands need one line, lookups report missing keys, and unknown input falls back to help.
Code
package main
import (
"fmt"
"strings"
)
// 命令表:新增子命令只需注册一行,不必扩展 switch
var commands = map[string]func(args []string) string{
"greet": func(args []string) string {
name := "stranger"
if len(args) > 0 {
name = args[0]
}
return "hello, " + name
},
"join": func(args []string) string { return strings.Join(args, "-") },
"help": func([]string) string { return "commands: greet join help" },
}
func main() {
lines := [][]string{
{"greet", "ada"},
{"join", "dev", "examples"},
{"help"},
{"unknown"},
}
for _, parts := range lines {
cmd, args := parts[0], parts[1:]
if fn, ok := commands[cmd]; ok {
fmt.Println(cmd, "->", fn(args))
} else {
fmt.Println(cmd, "->", "no such command; try help")
}
}
}How it works
Map Function Tables Dispatch Commands comes down to the function main.
The cycling part of this snippet is for _, parts := range lines.
Iteration is driven by for _, parts := range lines.
Key statements
for _, parts := range lines {
cmd, args := parts[0], parts[1:]
if fn, ok := commands[cmd]; ok {
fmt.Println(cmd, "->", fn(args))
} else {
fmt.Println(cmd, "->", "no such command; try help")
}
}
return "hello, " + name
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.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 Map Function Tables Dispatch Commands?
- The file is self-contained: run it directly, no dependencies to install beforehand.
Report a problem with this exampleOpens a pre-filled issue on GitHub.