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 parses named command-line options. Declare each option before calling flag.Parse, then read its value.
Typed declarations such as String and Int return pointers to values. After parsing, flag.Args contains positional arguments left after parsing stops.
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 does not begin with a flag marker, so later options remain positional. Provide useful defaults and descriptions because they appear in generated help. For several subcommands, use a separate flag.FlagSet for each command.
Enjoyed this? Get more software craft delivered to your inbox.