flag
Before You Start
- Applies to: Go 1.21+ (examples verified with Go 1.22) · Prerequisites: Base: Basic Syntax · Read time: about 10 min
Go's built-in Flag package implements command line argument parsing. The Flag package makes developing command line tools simpler.
Import
go
import flagTypes
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 argumentsExample
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>Complete Example
The program below runs as-is: copy it into a file and execute go run main.go, or paste it into the Go Playground.
go
package main
import (
"flag"
"fmt"
"strings"
)
func main() {
fs := flag.NewFlagSet("demo", flag.ContinueOnError)
name := fs.String("name", "world", "who to greet")
verbose := fs.Bool("v", false, "verbose output")
_ = fs.Parse([]string{"-name", "gopher", "-v"})
fmt.Println("hello,", *name)
if *verbose {
fmt.Println("flags:", strings.Join([]string{"-name", "-v"}, " "))
}
}Expected output:
text
hello, gopher
flags: -name -vCommon Pitfalls
- Define flags before
Parse. Callingflag.Parse()first means your flags are still unknown. - Bool flags need
=. Write-sex=false;-sex falseleavesfalseas a positional argument. - Use a
FlagSetin tests. A freshflag.NewFlagSetavoids the global state of the package-level helpers. - Positional arguments come after parsing. Read them from
fs.Args(). - Flags are not environment variables. Configuration from the environment must be read explicitly (for example with
os.Getenv).
Change Log
- 2026-10-14: Added "Before You Start" notes, a complete runnable example with expected output, common pitfalls, and this change log. Closed a code block that was left unterminated.
