The flag package parses command-line options and converts supplied values into supported Go types, including strings, integers, floating-point numbers, durations, and Booleans. It avoids hand-building syntax and conversion logic around os.Args. section 2.4
A typical flag workflow is:
- Declare a variable or obtain a pointer with a flag helper such as StringVar or String. section 2.4.1
- Provide the flag name, default value, and usage description. section 2.4.1
- Call flag.Parse before reading flag values. section 2.4 section 6.4.1
- Use flag.Arg to retrieve positional arguments separately from named flags, then validate missing input. section 6.4.1
Language and currency command lines
A greeting program can define -lang with default en, parse it, and pass the result to its greeting logic. A currency converter can define -from and -to, then accept the amount as a positional argument: go run . -from EUR -to CHF 10.50. The -to flag may default to EUR, while a missing amount produces an error and usage output. section 2.4.1 section 6.4.1
Listing 2.17 main.go: Using flags
package main
import (
"flag"
"fmt"
)
func main() {
var lang string
flag.StringVar(&lang,
"lang",
"en",
"The required language, e.g. en, ur...") #1
flag.Parse()
greeting := greet(language(lang))
fmt.Println(greeting)
}
// language represents a language
type language string
// phrasebook holds greeting for each supported language
var phrasebook = map[language]string{
...
}
// greet says hello to the world
func greet(l language) string {
...
}
Runnable Go code showing StringVar, a default language, flag.Parse, and conversion into a domain-specific language type. section 2.4.1



