1. Position arguments: what they are and why they are needed
Flags such as -title="..." look neat and official, but positional arguments are often treated as something you add only if you are lazy about making flags. In practice, positional arguments are a normal part of a command-line interface: git commit <message>, mkdir <dir>, go test <pkgs>. The only important thing is to parse them strictly and predictably, otherwise the user will have to read your program's mind, which is, unfortunately, a paid feature.
Positional arguments are the words on the command line that remain after the flags. For example, in the command:
app done -force 12
for the done command, the -force flag is a flag, and 12 is a positional argument, most likely the task ID.
In our teaching app, a simple todo CLI, positional arguments are especially convenient for things like done <id> or rm <id>. It is easier for a person to type one number than to remember that they need -id=12. But convenience comes with discipline: you must strictly check the number of arguments and carefully parse types.
2. Argument parsing: Parse → Args/NArg/Arg
First Parse, then Args/NArg/Arg
If you remember one sentence from this lecture, let it be this: read a command's positional arguments only after fs.Parse(argv) and only through fs.Args()/fs.NArg()/fs.Arg(i). Not through the original argv, not through “well, I can see that it is the second element,” and not through magic or intuition. Because the flag package can “eat” flags, shift emphasis, and leave you with exactly what is actually an argument.
The reason is simple: until Parse has run, you do not know what in argv was a flag and what was just text. flag parses according to its own rules, and your job is to accept the result. Like in a restaurant: first the waiter (Parse) takes the order, and then you (Args) get the dishes. If you start eating “by the menu list,” you may accidentally eat the salt cellar.
A tiny command handler skeleton looks like this:
package main
import (
"flag"
)
func runDone(argv []string) error {
fs := flag.NewFlagSet("done", flag.ContinueOnError)
if err := fs.Parse(argv); err != nil {
return err
}
// Only now is it safe to read fs.Args()/fs.NArg()/fs.Arg(i)
return nil
}
Why you cannot take positional arguments directly from argv
Sometimes a beginner writes this: “I have a done command, so argv[0] is the ID.” And indeed, in a simple case like app done 12, that will be true. But as soon as flags appear, things become trickier. For example:
app done -force 12
If you take argv[0], you will get the string -force, not 12. And then you will very sincerely parse -force through strconv.Atoi, getting an error that looks like “why is the number not a number.” At that point, the user already starts doubting whether they know how to count, even though the problem is not with them.
fs.Parse(argv) is exactly what you need to separate flags from positional arguments and then hand you a “clean” list via fs.Args(). So you can think of argv as raw data and fs.Args() as cleaned and ready to cook.
Here is a small “raw vs cleaned” example:
package main
import (
"flag"
"fmt"
)
func demo(argv []string) {
fs := flag.NewFlagSet("demo", flag.ContinueOnError)
_ = fs.Bool("force", false, "force mode")
_ = fs.Parse(argv)
fmt.Println("raw argv:", argv) // raw argv: [-force 12]
fmt.Println("pos args:", fs.Args()) // pos args: [12]
}
3. Tools Args, NArg, Arg(i)
Once you have called Parse, a FlagSet has three main ways to work with positional arguments. They are similar, but fit different situations. Think of them as three ways to “look at the queue”: you can get its length, take an element by index, or get the whole list.
Summary table:
| Method | What it gives | When it is convenient |
|---|---|---|
|
number of positional arguments | when the command requires “exactly N” |
|
positional argument by index | when you need a specific argument, for example an ID |
|
slice of all positional arguments | when there are many arguments or you want to iterate over them in a loop |
In our todo CLI, the typical contracts are: done needs exactly one argument, list usually needs zero (we do filters with flags), and add sometimes wants “everything that remains is the task text,” that is, Args().
An example of a strict “exactly one argument” check:
package main
import (
"errors"
"flag"
"fmt"
)
var ErrUsage = errors.New("usage")
func runDone(argv []string) error {
fs := flag.NewFlagSet("done", flag.ContinueOnError)
if err := fs.Parse(argv); err != nil {
return fmt.Errorf("%w: %v", ErrUsage, err)
}
if fs.NArg() != 1 {
return fmt.Errorf("%w: usage: app done <id>", ErrUsage)
}
return nil
}
Here ErrUsage is a marker for “the user ran it incorrectly.” We wrap it with %w so that later we can recognize the error with errors.Is. The idea behind wrapping with %w is precisely that we preserve the original cause inside the new error.
4. The positional-argument contract
A CLI command is a small agreement between a human and a program. And positional arguments in that agreement are responsible for two things: count and meaning. When you design a command, you can almost always express the rule in words: “the done command requires one argument — the task id, an integer.” That rule must be implemented in code literally, without telepathy.
The good news is that implementing this in Go is very simple. The bad news is that “simple” often encourages “good enough,” and then the command starts silently ignoring extra arguments. Silence in a CLI is almost always bad: the user thinks everything was applied, while your program just threw half the command into the trash.
Let's make a small helper for checking the number of arguments. It will return an ErrUsage error so that classification stays stable.
package main
import (
"errors"
"flag"
"fmt"
)
var ErrUsage = errors.New("usage")
func requireNArgs(fs *flag.FlagSet, n int, usage string) error {
if fs.NArg() != n {
return fmt.Errorf("%w: usage: %s", ErrUsage, usage)
}
return nil
}
Notice: this is not “a library for the ages,” but such a helper makes command handlers much more readable, especially when there are many commands.
5. Type parsing and meaningful errors
After you check the number of positional arguments, the second layer of the contract begins: types. If we expect a number, we need to convert the string into an int and handle the error correctly. In Go, this is done through strconv.Atoi. The Atoi error itself is useful, but for the user the context is often more important: which exact argument is broken and what value was received.
For the done command, it looks like this:
package main
import (
"fmt"
"strconv"
)
func parseID(s string) (int, error) {
id, err := strconv.Atoi(s)
if err != nil {
return 0, fmt.Errorf("id must be integer, got %q", s)
}
return id, nil
}
Here %q prints the string in quotes, which is useful when the user accidentally passed spaces or strange symbols. For example, got " 12" immediately suggests that there is a space somewhere.
Now let's combine this with ErrUsage (because “id is not a number” is almost always a usage error):
package main
import (
"errors"
"fmt"
)
var ErrUsage = errors.New("usage")
func parseIDUsage(s string) (int, error) {
id, err := parseID(s)
if err != nil {
return 0, fmt.Errorf("%w: %v", ErrUsage, err)
}
return id, nil
}
We use wrapping through %w again so that ErrUsage does not get lost in the chain of causes. This matches the general approach of “wrap the error, but do not lose the original cause.”
6. Flag parsing errors and error classification
Positional arguments are only half the story. The other half is the errors that fs.Parse(argv) can return. And this is an important part of UX: when a person makes a mistake in the flags, that is also a usage error. For example, they typed an unknown flag, forgot a value, or mixed up a type. Such errors should not be masked as an “internal failure” of the program.
That is why there is a standard trick in a command handler: if Parse returns an error, we wrap it in ErrUsage and pass it upward. We do not print it here (the top level will print it), but we classify it. And again: wrapping.
package main
import (
"errors"
"flag"
"fmt"
)
var ErrUsage = errors.New("usage")
func parseFlags(fs *flag.FlagSet, argv []string) error {
if err := fs.Parse(argv); err != nil {
return fmt.Errorf("%w: %v", ErrUsage, err)
}
return nil
}
Why is %w not used here for err? Because our goal is classification by ErrUsage, not necessarily preserving the entire low-level structure of the flag error. In some projects they do use %w as well (for example, fmt.Errorf("%w: %w", ErrUsage, err)), but then the error has a “dual nature,” and you need to think more carefully about what errors.Is will find.
7. End-to-end examples: done and add commands
Done command: flags + positional ID
Now let's assemble everything into one coherent piece of code that actually resembles a command. Suppose we have a done command that accepts the -force flag, a demo flag just to show how Parse separates flags, and one positional argument <id>.
package main
import (
"errors"
"flag"
"fmt"
"os"
"strconv"
)
var ErrUsage = errors.New("usage")
func runDone(argv []string) error {
fs := flag.NewFlagSet("done", flag.ContinueOnError)
fs.SetOutput(os.Stderr)
force := fs.Bool("force", false, "mark done even if already done (demo)")
if err := parseFlags(fs, argv); err != nil {
return err
}
if err := requireNArgs(fs, 1, "app done [flags] <id>"); err != nil {
return err
}
id, err := parseIDUsage(fs.Arg(0))
if err != nil {
return err
}
fmt.Printf("done: id=%d force=%v\n", id, *force) // done: id=12 force=true
return nil
}
func parseID(s string) (int, error) {
id, err := strconv.Atoi(s)
if err != nil {
return 0, fmt.Errorf("id must be integer, got %q", s)
}
return id, nil
}
The important thing here is that we call fs.Arg(0) only after requireNArgs. It is like fastening your seat belt before driving off: you can do without it, but later it will be very regrettable and very loud.
Add command: when there are “many” arguments and Args() is needed
The add command usually adds a task with text. A common UX model is: everything that remains after the flags is the task text. That is, we support cases like:
app add "Buy milk"
app add -priority=2 Buy milk today
Here it is more convenient to take fs.Args(), join the words back together, and get the title. This is a good example of why Args() is sometimes more convenient than Arg(0).
package main
import (
"errors"
"flag"
"fmt"
"strings"
)
var ErrUsage = errors.New("usage")
func runAdd(argv []string) error {
fs := flag.NewFlagSet("add", flag.ContinueOnError)
priority := fs.Int("priority", 1, "task priority (demo)")
if err := parseFlags(fs, argv); err != nil {
return err
}
if fs.NArg() == 0 {
return fmt.Errorf("%w: usage: app add [flags] <title...>", ErrUsage)
}
title := strings.Join(fs.Args(), " ")
fmt.Printf("add: %q (priority=%d)\n", title, *priority) // add: "Buy milk today" (priority=2)
return nil
}
This approach gives a pleasant UX: the user does not have to write quotes if they do not want to. But even here the contract must be strict: if NArg() returns 0, then there is no title — and that is a usage error.
8. A mini diagram of argv parsing inside a command
Sometimes it is useful to visually fix what is happening so that you stop fighting argv like a hydra. The diagram below shows the typical execution flow of a command handler:
flowchart TD
A["command argv: []string"] --> B["fs.Parse(argv)"]
B -->|err != nil| U[return ErrUsage + parse error]
B -->|ok| C["fs.NArg() / fs.Args()"]
C -->|contract mismatch| V[return ErrUsage + usage string]
C -->|match| D[parse types: Atoi / etc]
D -->|type error| W["return ErrUsage + 'id must be int'"]
D -->|ok| E[execute command]
E --> F[return nil]
The meaning of this diagram is simple: first we clean up the input (Parse), then we check the contract (NArg), then we parse types (Atoi), and only then do we work. This is a direct path to making a CLI behave predictably, instead of like “a lottery of a random index name.”
9. Typical mistakes when parsing positional arguments
Mistake #1: reading positional arguments from argv instead of fs.Args().
Such code often “works” on examples without flags, and then suddenly breaks when -force or any other flag appears. The problem is that argv is raw input, while fs.Args() is already the parsed result, where the flags are separated. So first Parse, then fs.Args() — and your nervous system will thank you.
Mistake #2: calling fs.Arg(0) without checking fs.NArg().
If the user forgot an argument, the program will reach for Arg(0) and get an empty string, or it will start parsing “nothing” as a number. In the best case you get an unclear error, in the worst case behavior that looks like “everything worked, but why is id=0?” It is better to check the number of arguments first as part of the command contract.
Mistake #3: silently ignoring extra arguments.
The command done 12 extra should either explicitly accept extra as part of the meaning, which is strange for done, or honestly say: “too many arguments, usage: …”. Silent ignoring turns the CLI into a guessing game: the user thinks extra was taken into account, while your program just pretended it did not exist.
Mistake #4: returning bare strconv.Atoi without context.
If you simply do return strconv.Atoi(fs.Arg(0)), the user gets a message at the level of “invalid syntax” and has to guess what exactly is wrong. It is much better to add context: which argument you expected, which value you got, and what it should have been. This is especially useful when the command accepts multiple numbers.
Mistake #5: not distinguishing usage errors from execution errors.
When Parse fails, when there are not enough arguments, when id is not a number — this is almost always a usage error that should be marked as ErrUsage so that the top level can correctly choose an exit code and, if desired, show usage. The idea of “errors as values” and the practice of wrapping causes with %w help build such classification without text analysis.
GO TO FULL VERSION