typestar

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

  1. Each call returns a pointer to the parsed value.
  2. flag.Args holds what was left after the flags.
  3. A FlagSet keeps a test from touching the global one.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 2 in Programs & logging, step 14 of 26 in Standard library & project layout.

← Previous Next →