flag.Parse parses the defined command-line flags and assigns their values to the variables registered with the flag package. Call it after defining flags, commonly during initialization, before main uses those values. section 2.1.1
Listing 2.2 Hello World using command-line flags
package main
import (
"flag" #1
"fmt"
)
var name = flag.String("name", "World", "A name to say
hello to.") #2
var inSpanish bool #3
func init() {
flag.BoolVar(&inSpanish, "spanish", false, "Use
Spanish language.")
flag.BoolVar(&inSpanish, "s", false, "Use Spanish
language.") #4
flag.Parse() #5
}
func main() {
if inSpanish {
fmt.Printf("Hola %s!\n", *name) #6
} else {
fmt.Printf("Hello %s!\n", *name)
}
}
A complete Go CLI defines string and Boolean flags, calls flag.Parse, and uses the resulting values to choose its output. section 2.1.1
Parsing also determines how invalid, repeated, and incompatible arguments behave:
- Invalid flags or values trigger an early exit with built-in usage information. section 2.1.1
- Repeated Boolean aliases are processed in declaration order, so a later value can overwrite an earlier one. section 2.1.1
- Incompatible types are rejected rather than coerced; time.Duration is an exception with automatic conversion from an integer. section 2.1.1

