Skip to content

Command line flags

The flag package provides standard flag parsing. Flags can be of type string, int, bool, duration, etc. Use flag.String, flag.Int, etc., then call flag.Parse().

Define flags for name and age.

package main
import (
"flag"
"fmt"
)
func main() {
name := flag.String("name", "World", "name to greet")
age := flag.Int("age", 0, "age of the person")
verbose := flag.Bool("verbose", false, "enable verbose output")
flag.Parse()
fmt.Printf("Hello, %s\n", *name)
if *verbose {
fmt.Printf("Age: %d\n", *age)
}
}

Output (run as ./greet -name Alice -age 30 -verbose)

Section titled “Output (run as ./greet -name Alice -age 30 -verbose)”
Terminal window
Hello, Alice
Age: 30