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.
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)
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?