A command-line argument is a value supplied when a program runs from a command-line interface. Go distinguishes named flags, such as -lang or -from, from positional arguments, such as the amount following currency flags. section 2.4 section 6.4.1
Use Go’s flag package to define, parse, and retrieve command-line input:
- Define a typed flag with a name, default value, and description; StringVar stores the result in a variable, while String returns a pointer. section 2.4.1
- Call flag.Parse after defining flags and before accessing their values. section 2.4 section 6.4.1
- Retrieve a positional value with flag.Arg(0), then report missing input through standard error, usage information, and a nonzero exit. section 6.4.1
- Prefer the flag package when parsing typed values, rather than implementing option syntax and type conversion manually through os arguments. section 2.4
Greeting and currency-conversion CLIs
A greeting program can accept -lang ur and default to en when the flag is absent. A currency converter can accept -from EUR -to USD 413.98, using the flags for currencies and the first positional argument for the amount. Missing or unsupported values should be checked as part of the CLI’s input handling. section 2.4.1 section 2.5 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 {
...
}
Inspect a complete Go program that declares a string flag, parses it, and passes the resulting language to greeting logic. section 2.4.1













