Parse command-line arguments and flags
Parse command-line arguments and flags
A command-line interface (CLI) receives arguments as strings. os.Args[0] identifies the invoked program; os.Args[1:] holds its arguments. A flag.FlagSet with ContinueOnError lets a function return parsing errors rather than terminating the process. This example passes a fixed argument slice so you can test it without a shell.
package main
import ( "errors" "flag" "fmt" "io")
func parse(args []string) (string, int, error) { f := flag.NewFlagSet("report", flag.ContinueOnError) f.SetOutput(io.Discard) n := f.Int("limit", 10, "maximum rows") if err := f.Parse(args); err != nil { return "", 0, err } if f.NArg() != 1 || *n < 1 { return "", 0, errors.New("expected one file and positive limit") } return f.Arg(0), *n, nil}func main() { name, n, err := parse([]string{"-limit=3", "sales.csv"}) fmt.Println(name, n, err == nil)}Int registers a typed option with a default and returns a pointer. Parse updates it and leaves positional arguments in Args. Validate both the number of operands and semantic constraints after parsing. The example discards parser diagnostics only because the caller inspects the returned error; a real CLI should report it.
Expected output:
sales.csv 3 trueFlag order and the separator
package main
import ( "errors" "flag" "fmt" "io")
func parse(args []string) (string, int, error) { f := flag.NewFlagSet("report", flag.ContinueOnError) f.SetOutput(io.Discard) n := f.Int("limit", 10, "maximum rows") if err := f.Parse(args); err != nil { return "", 0, err } if f.NArg() != 1 || *n < 1 { return "", 0, errors.New("expected one file and positive limit") } return f.Arg(0), *n, nil}func main() { _, _, err := parse([]string{"sales.csv", "-limit=3"}) fmt.Println(err != nil) name, n, err := parse([]string{"--", "-daily.csv"}) fmt.Println(name, n, err == nil)}The standard flag parser stops at the first non-flag argument or --. A flag after a filename is therefore an extra operand in this contract. The separator allows filenames beginning with a hyphen. Shell quoting happens before Go receives the arguments; never join and split os.Args to reconstruct them.
Expected output:
true-daily.csv 10 trueTry it locally
Use parse with -limit=0 and one filename; print whether validation fails. Then use only a filename and print the default limit.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
CLI 01: Parse command-line arguments and flags
Check the lesson objective before moving on.
Where does the standard flag parser stop?
Why use ContinueOnError?