Command-Line Flags
Parse named flags and positional arguments with flag; typed flag values are pointers, and parsing stops at the first positional argument.
The flag package reads named command-line options, also called flags, such as -output report.txt. Declare each option before calling flag.Parse, then use the value the user supplied or its default.
Functions such as flag.String return a pointer, a value that refers to another value. Use *output to read the flag's text. After parsing, flag.Args returns positional arguments, values without a flag name.
package main
import (
"flag"
"fmt"
)
func main() {
output := flag.String("output", "stdout", "destination")
flag.Parse()
fmt.Println("output:", *output)
fmt.Println("files:", flag.Args())
}In production
The standard parser stops at the first argument that is not a flag, so later options are treated as positional values. Set a useful default and description because they appear in the generated help. For a program with subcommands, create a separate flag.FlagSet, a parser with its own options, for each command.