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.

GoCli Tooling

Code

gosnippet
36 lines
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

FAQ

How do you run Map Function Tables Dispatch Commands?
The file is self-contained: run it directly, no dependencies to install beforehand.