1. CLI arguments: what really gets into a Go program
When people hear "command-line arguments," they often imagine a single string like todo add buy milk. But in Go you get already split pieces — a slice of strings []string. That is convenient, but it is important to understand the rules: the first element is the program name, and everything after that is what the user typed, in already "parsed" form.
Let's poke at this by hand — we will write a tiny program that just prints the input.
package main
import (
"fmt"
"os"
)
func main() {
fmt.Printf("os.Args = %#v\n", os.Args)
fmt.Println("program:", os.Args[0]) // program: ./app (example)
}
If you run it like this: ./app hello world, then os.Args will look roughly like []string{"./app", "hello", "world"}. In other words, Go no longer sees "the whole command"; it sees a list of "tokens".
This leads to the first important conclusion: when you parse os.Args, you are in fact designing a mini-language of input that lives inside your command. And that mini-language will either be tidy or become a "surprise" for everyone, including you a week later.
2. The first win: one argument — and it seems so simple
The first 10 minutes are usually inspiring. Need to accept one required argument? Easy: check the length — read os.Args[1]. Example: our "task manager" skeleton accepts a task title.
package main
import (
"fmt"
"os"
)
func main() {
if len(os.Args) < 2 {
fmt.Println("missing TITLE") // missing TITLE
return
}
title := os.Args[1]
fmt.Println("title:", title) // title: Buy milk
}
And yes: "it works!". Until the next requirement appears: "let's add priority too." Then "let's mark done." Then "let's print help." Then "let's allow a name that starts with -." And this is where os.Args starts hinting that it is not breaking — we are the ones breaking, because we are trying to hand-roll something that has already been invented.
3. As soon as a number appears — manual parsing starts to swell
As soon as you add a numeric argument, two things appear in the code: argument count checks and parsing error handling. That is normal, but notice how quickly the "boilerplate" grows.
Suppose we want: todo TITLE PRIORITY, where PRIORITY is a number.
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
if len(os.Args) != 3 {
fmt.Println("Usage: todo TITLE PRIORITY") // Usage: todo TITLE PRIORITY
return
}
title := os.Args[1]
priority, err := strconv.Atoi(os.Args[2])
if err != nil {
fmt.Println("PRIORITY must be int:", err) // PRIORITY must be int: ...
return
}
fmt.Println("task:", title, "priority:", priority) // task: Buy milk priority: 3
}
So far, still manageable. But it is important to notice: we are already starting to write "our own protocol": where each thing goes, how many arguments there are, what format they use, what error messages look like. And this is only two parameters. Once there are more, your main starts to look like a test on "branches and suffering".
4. When options appear: manual parsing falls apart
Positional arguments (the ones that just go in order) are good when there are few of them and the order is natural. For example: cat FILE, go test ./..., git clone URL. But as soon as you add optional settings, positional arguments turn into a game of "guess what the user meant".
Let's imagine the contract for our program:
- required: TITLE
- optional: priority (default 1)
- optional: done (default false)
The user will naturally want to write something like:
- todo -title "Buy milk" -priority 3
- todo -title "Buy milk" -done
- todo -title "Buy milk"
If we try to do this manually with os.Args, we quickly end up in a swamp: we need to walk through arguments, determine "is this a key or a value," check that a key has a value after it, and so on. Here is an example of "manual flag parsing" in the style of "I just tried it, and now I already dislike it."
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
title := ""
priority := 1
done := false
for i := 1; i < len(os.Args); i++ {
switch os.Args[i] {
case "-title":
if i+1 >= len(os.Args) {
fmt.Println("missing value for -title") // missing value for -title
return
}
title = os.Args[i+1]
i++
case "-priority":
if i+1 >= len(os.Args) {
fmt.Println("missing value for -priority") // missing value for -priority
return
}
p, err := strconv.Atoi(os.Args[i+1])
if err != nil {
fmt.Println("bad -priority:", err) // bad -priority: ...
return
}
priority = p
i++
case "-done":
done = true
default:
fmt.Println("unknown argument:", os.Args[i]) // unknown argument: ...
return
}
}
fmt.Println("title:", title, "priority:", priority, "done:", done)
}
Yes, this works... until you add:
- short forms (-p 3),
- the format -priority=3,
- -- as "positional only from here on",
- repeatable flags,
- human-readable help,
- proper error messages and a single usage format.
You are literally starting to write your own mini version of flag, only worse, because you are doing it in the evening, with a tired brain, no tests, and no desire to maintain "yet another bicycle."
5. Typical pitfalls of manual parsing
There are several places where hand-written parsing with os.Args is especially unpleasant. It is worth feeling them in advance so that later you do not wonder why "it all seemed so simple."
Imagine that the user wants to add a task with a title that starts with a hyphen. For example, the task "-reboot router" (yes, it is odd, but in real life anything happens). In a manual parser, you usually interpret everything that starts with - as a flag. And then you get a conflict: is it a title or a parameter?
Then comes the story of the "-- marker" (which many CLI tools use), but if you did not build it into the design, you either break UX or invent hacks.
Another source of pain is different syntactic forms. The user may write -priority 3, or they may write -priority=3. If your parser supports only one, people will ask, "why not like in normal programs?" If it supports both, the code grows.
And one more thing that beginners often underestimate: you almost always want validation "by meaning." The parser will convert a string to an int, but it does not know that priority must be 1..5. In the manual version, you start smearing rules across the code: some checks at parse time, some after, some somewhere "along the way."
That is how a program appears in which you can no longer safely add a new parameter: it feels like any change might break something in an unexpected branch. Not because Go is weak, but because the manual input protocol has started to live its own life.
6. Maintenance: help, tests, and responsibility boundaries
Help and usage easily drift out of sync
The next stage of pain is a hint to the user. At first you write something like:
fmt.Println("Usage: todo -title <text> [-priority N] [-done]")
Then you add -format, -limit, -verbose, and... forget to update usage. Or you update it in one place, but there are two more "return with error" branches where usage is printed too, but in a different format.
As a result, the user gets three different hints depending on exactly how they made a mistake. And you get the feeling that things have kind of spread everywhere.
This is an important CLI design principle: help should be generated from a single source of truth. If help lives separately from the parameter definitions, it will always lag behind. That is why good flag libraries (and the standard flag) make the flag description tied to its declaration, and build help automatically.
When parsing gets mixed with logic, testing becomes painful
There is a very practical reason why manual parsing with os.Args quickly starts to "break": it almost always ends up right inside main, next to the program logic.
At first this looks logical: "well, where else?" But then you want to test business logic. And how do you test it if it is in main and reads os.Args directly?
It creates an unpleasant combination:
- to check the logic, you have to run the program as a process,
- to check different argument variants, you have to build/replace os.Args,
- to check error messages, you have to capture console output.
Yes, you can do it, but for a beginner it is usually uncomfortable, and most often no tests appear at all. And without tests, your manual parser quickly turns into a minefield.
When you use the standard flag parser, you usually move configuration into a struct, do "parse → validate → execute," and the code becomes easier to test. Not because it is "fashionable," but because you get a boundary between "input" and "logic."
Mini refactor around os.Args: you can see that we are writing our own flag
To really "feel" the motivation, let's do a small refactor of our teaching app. We will not hook up flag yet (that is a separate topic), but we will do what is often done in real code at the first stage: extract configuration and a parsing function. That is useful even if you are still reading os.Args manually, because it makes life easier for the brain.
First, let's define the configuration. Notice: here we store values, not "pointers to something." We want the rest of the program not to know anything about os.Args at all.
package main
type Config struct {
Title string
Priority int
Done bool
}
Now let's make a parser. It is still manual, but it already returns (Config, error) — as we are used to from lectures about errors.
package main
import (
"fmt"
"os"
)
func parseArgs(args []string) (Config, error) {
if len(args) < 2 {
return Config{}, fmt.Errorf("missing TITLE")
}
return Config{Title: args[1], Priority: 1, Done: false}, nil
}
And main becomes thinner:
package main
import (
"fmt"
"os"
)
func main() {
cfg, err := parseArgs(os.Args)
if err != nil {
fmt.Println("error:", err) // error: missing TITLE
return
}
fmt.Println("accepted:", cfg.Title) // accepted: Buy milk
}
It seems better. But now imagine that you add -priority and -done, and parseArgs starts growing again. You gradually come to the conclusion: "we are building a universal argument parser." That is... yes. Exactly. You are starting to make flag, only in a stripped-down, incompatible, and untested form.
And this is the moment when you need to honestly say: manual parsing of os.Args is good as a learning stage and as a solution for "1-2 parameters without variations." But if the CLI is even slightly like a real one, it is time to use the standard mechanism.
7. What a normal parser should do and why that is flag
If you collect the requirements for a "normal" CLI parser, it becomes clear why it should not be hand-written, especially at the start.
A proper solution should support a clear syntax where there are flags (named parameters) and positional arguments (required things in order). It should handle errors consistently and print help so that it matches the real parameters. It should provide defaults and let you validate meaning separately from type parsing. And preferably it should be standard, so that other people do not have to learn your unique "argument dialect" as if it were a new programming language.
In Go, there is a standard package for this: flag. Its main value is not that it is "magical," but that it handles the boring part: it parses arguments neatly and predictably, freeing you for application logic.
8. Typical mistakes when parsing os.Args by hand
Mistake #1: reading os.Args[1] without checking the length.
This is the most common cause of panic for beginners. In Go, slices do not forgive "maybe there is an element there." If there are no arguments, accessing os.Args[1] causes a runtime panic. Even if you are sure that "the user will always pass something," practice quickly explains that the user is a creative person.
Mistake #2: mixing argument parsing and business logic execution in one place.
While the program is small, it feels faster. But as soon as the second validation rule, the third error message, and the fourth parameter appear, the code turns into mush. Life is much calmer when you have "first parse, then validate, then execute."
Mistake #3: treating positional arguments as a universal solution.
Positional arguments are good while there are few of them. When there are many, the user confuses the order, and you add checks like "len exactly N," then "N or N+1," then "if the third argument looks like a number..." It is a path to an unpredictable interface.
Mistake #4: writing usage manually in several places.
Today you print Usage: ... in one place, tomorrow you add another error branch and forget to put it there too. In the end, the interface becomes inconsistent. If help is part of UX, then a mismatch between help and the actual parameters feels like a bug.
Mistake #5: "quietly swallowing" unknown arguments.
Sometimes beginners make a parser that ignores anything unfamiliar. It seems like "fewer errors." In reality, it makes things worse: the user mistypes -priorty, and the program silently runs with the default. That is not an error — it is a trap.
GO TO FULL VERSION