import "flag" var port int func main() { fs := flag.NewFlagSet("Example", flag.ExitOnError) fs.IntVar(&port, "port", 8080, "port number") fs.Parse(os.Args[1:]) }
import "flag" var ( port int mode string config string ) func main() { fs := flag.NewFlagSet("Example", flag.ExitOnError) fs.IntVar(&port, "port", 8080, "port number") fs.StringVar(&mode, "mode", "dev", "mode type (dev or prod)") configCmd := fs.String("config", "", "configuration file") fs.Parse(os.Args[1:]) if fs.Args()[0] == "config" { fs.Parse(fs.Args()[1:]) fmt.Println("config command") fmt.Printf("Port=%d, Mode=%s\n", port, mode) fmt.Printf("Using config=%s\n", *configCmd) return } fmt.Println("app command") fmt.Printf("Port=%d, Mode=%s\n", port, mode) }
import "flag" var ( port int value string ) func main() { rootFS := flag.NewFlagSet("root", flag.ExitOnError) rootFS.IntVar(&port, "port", 8080, "port number") subFS := flag.NewFlagSet("sub", flag.ExitOnError) subFS.StringVar(&value, "val", "", "custom value") if len(os.Args) < 2 { fmt.Println("Need a sub-command") os.Exit(1) } switch os.Args[1] { case "root": rootFS.Parse(os.Args[2:]) fmt.Printf("Port=%d\n", port) case "sub": subFS.Parse(os.Args[2:]) fmt.Printf("Value=%s\n", value) default: fmt.Println("Unknown command") os.Exit(1) } }This example demonstrates working with multiple `FlagSets`. Each `FlagSet` can have its own set of flags and sub-commands. The `os.Args` array is used to determine the root command and which `FlagSet` should be used to parse the sub-commands and sub-flags. In conclusion, the `FlagSet` type is a very useful and flexible tool provided by the `flag` package in Go. It provides support for complex flag sets that can be grouped and sub-grouped for better organization.