Go by Example: Command-Line Subcommands

The following example demonstrates how to use subcommands in Go:

package main

import (

func main() {
	cmd := flag.NewFlagSet("create", flag.ExitOnError)
	createName := cmd.String("name", "", "Name of the resource to create")

	cmd2 := flag.NewFlagSet("delete", flag.ExitOnError)
	deleteName := cmd2.String("name", "", "Name of the resource to delete")

	if len(os.Args) < 2 {
		fmt.Println("expected 'create' or 'delete' subcommands")

	switch os.Args[1] {
	case "create":
		fmt.Println("Creating resource:", *createName)
	case "delete":
		fmt.Println("Deleting resource:", *deleteName)
		fmt.Println("expected 'create' or 'delete' subcommands")

In this example, we use the flag.NewFlagSet function to create two different sets of flags, one for each of our two subcommands create and delete. We then use a switch statement to parse the subcommand and set the corresponding flags. Finally, we use the values of the flags to take appropriate action.

Here’s an example run of the program:

$ go run main.go create --name=test
Creating resource: test


Leave a Reply

Your email address will not be published. Required fields are marked *