Skip to content

flag

Go's built-in Flag package implements command line argument parsing. The Flag package makes developing command line tools simpler.

Import

go
import flag

Types

Supported types include:

  • bool
  • int
  • int64
  • uint
  • uint64
  • float
  • float64
  • string
  • duration

Definition

Use flag.Type() to define, the return value is a pointer:

go
name := flag.String("name", "Zhang San", "Name")
age := flag.Int("age", 15, "Age")
sex := flag.Bool("sex", true, "Gender")

You can also use flag.TypeVar() to define:

go
var name string
var age int
var sex bool
flag.StringVar(&name, "name", "Zhang San", "Name")
flag.IntVar(&age, "age", 15, "Age")
flag.BoolVar(&sex, "sex", true, "Gender")

Parsing

Parse arguments by calling flag.Parse(). Supported command line argument formats include:

  • -flag xxx
  • --flag xxx
  • -flag=xxx
  • --flag=xxx

Boolean type arguments must use an equals sign. Flag parsing stops before the first non-command-line argument.

Others

go
func Args() []string // Returns all non-command arguments

func NArg() int // Returns the number of non-command-line arguments

func NFlag() int // Returns the number of command-line arguments

Example

go
var name string
var age int
var sex bool
flag.StringVar(&name, "name", "Zhang San", "Name")
flag.IntVar(&age, "age", 15, "Age")
flag.BoolVar(&sex, "sex", true, "Gender")

flag.Parse()
fmt.Println(name, age, sex)

After compiling, start the program from the command line:

powershell
PS D:\WorkSpace\Code\GoProject\bin> .\go_build_GoProject_src_main.exe
Zhang San 15 true
PS D:\WorkSpace\Code\GoProject\bin> .\go_build_GoProject_src_main.exe -h
Usage of D:\WorkSpace\Code\GoProject\bin\go_build_GoProject_src_main.exe:
  -age int
        Age (default 15)
  -name string
        Name (default "Zhang San")
  -sex
        Gender (default true)
PS D:\WorkSpace\Code\GoProject\bin> .\go_build_GoProject_src_main.exe -age 15 -name "Li Si" -sex=false
Li Si 15 false
PS D:\WorkSpace\Code\GoProject\bin>

Golang by www.golangdev.cn edit