Understand the contract
The flag package parses named command-line options into typed values. Define flags before calling flag.Parse, then validate the resulting configuration. Syntax parsing can establish that a value is an integer, while application validation decides whether that integer is an acceptable repetition count.
flag.String and flag.Int return pointers to the values that parsing will populate. Read them after Parse by dereferencing those pointers. The default command-line FlagSet also handles -h for help. Positional arguments remain accessible through flag.Args after option parsing has finished.
Work through the example
Save the example as main.go and run go run . -name Ada -repeat 2. It prints two greetings. The explicit upper bound keeps this teaching command small. The count check belongs after parsing because defaults and explicit flags should pass through the same validation rules.
package main
import (
"flag"
"fmt"
)
func main() {
name := flag.String("name", "Go", "name to greet")
repeat := flag.Int("repeat", 1, "number of greetings (1-10)")
flag.Parse()
if *repeat < 1 || *repeat > 10 { fmt.Println("repeat must be 1-10"); return }
for i := 0; i < *repeat; i++ { fmt.Println("Hello,", *name) }
}Watch this boundary
The standard flag parser stops parsing at the first non-flag argument. Do not assume flags placed after a positional filename are consumed. For reusable parsing tests, create a separate FlagSet rather than repeatedly using global flag variables, which retain process-wide state.
Practice with a changed input
Run the command with -h, an invalid integer and repeat zero. Add a positional argument and inspect flag.Args so the boundary between options and operands is explicit.
Lesson 38 of 50
View the full Go basics seriesReferences & further reading
Need help with your Go backend?
I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.
Explore Go consulting services