How do I build nested subcommands using flag in Go?

In Go, you can build nested subcommands using the `flag` package alongside custom logic to parse commands. This allows you to create a structured command-line interface that can handle multiple levels of commands, making your application more organized and easier to use.

Go, nested subcommands, flag package, command-line interface, CLI
This guide explains how to implement nested subcommands in Go using the flag package, which is essential for building a robust command-line application.
package main import ( "flag" "fmt" "os" ) func main() { // Creating the root command rootCmd := flag.NewFlagSet("app", flag.ExitOnError) createCmd := flag.NewFlagSet("create", flag.ExitOnError) deleteCmd := flag.NewFlagSet("delete", flag.ExitOnError) // Create command flags createName := createCmd.String("name", "", "Name of the item to create") // Delete command flags deleteID := deleteCmd.String("id", "", "ID of the item to delete") if len(os.Args) < 2 { fmt.Println("expected 'create' or 'delete' subcommands") os.Exit(1) } switch os.Args[1] { case "create": createCmd.Parse(os.Args[2:]) fmt.Println("Item created with name:", *createName) case "delete": deleteCmd.Parse(os.Args[2:]) fmt.Println("Item deleted with ID:", *deleteID) default: fmt.Println("expected 'create' or 'delete' subcommands") os.Exit(1) } }

Go nested subcommands flag package command-line interface CLI