Command-line flags in Go
The flag package declares, parses and documents the interface.
func parseArgs(args []string) (string, int, bool, []string, error) {
set := flag.NewFlagSet("typestar", flag.ContinueOnError)
set.SetOutput(io.Discard)
lang := set.String("lang", "go", "language to practice")
seconds := set.Int("seconds", 60, "sprint length")
editor := set.Bool("editor", false, "editor mode")
if err := set.Parse(args); err != nil {
return "", 0, false, nil, fmt.Errorf("parse flags: %w", err)
}
return *lang, *seconds, *editor, set.Args(), nil
}
How it works
- Each call returns a pointer to the parsed value.
flag.Argsholds what was left after the flags.- A FlagSet keeps a test from touching the global one.
Keywords and builtins used here
boolerrorfuncifintreturnstring
The run, in numbers
- Lines
- 13
- Characters to type
- 466
- Tokens
- 128
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 73 seconds.
Step 1 of 2 in Programs & logging, step 14 of 26 in Standard library & project layout.