import ( "flag" "fmt" ) func main() { var count int var name string flags := flag.NewFlagSet("example", flag.ExitOnError) flags.IntVar(&count, "count", 0, "number of times to repeat") flags.StringVar(&name, "name", "world", "name to greet") flags.Parse(os.Args[1:]) for i := 0; i < count; i++ { fmt.Printf("Hello, %s!\n", name) } }
import ( "flag" "fmt" "os" ) func main() { flags := flag.NewFlagSet("example", flag.ExitOnError) helloCmd := flags.NewFlagSet("hello", flag.ExitOnError) helloName := helloCmd.String("name", "world", "name to greet") goodbyeCmd := flags.NewFlagSet("goodbye", flag.ExitOnError) if len(os.Args) <= 1 { fmt.Println("hello or goodbye subcommand is required") os.Exit(1) } switch os.Args[1] { case "hello": helloCmd.Parse(os.Args[2:]) fmt.Printf("Hello, %s!\n", *helloName) case "goodbye": goodbyeCmd.Parse(os.Args[2:]) fmt.Println("Goodbye!") default: fmt.Println("hello or goodbye subcommand is required") os.Exit(1) } }In this example, we define two subcommands ("hello" and "goodbye") using the "NewFlagSet()" method of the "FlagSet" type. We then parse command-line arguments using the "Parse()" method of the appropriate subcommand flag set. Finally, we use the subcommand name and flag values to execute the appropriate action.