1. Why separate stdout and stderr
When you write a console program, it is very easy to think: “Well, I am printing to the console — what difference does it make where exactly?” But the operating system, and most CLI tools in the world, have an old and very sensible agreement: normal data goes to stdout, and diagnostics go to stderr.
This is not philosophy and it is not aesthetics. It is a practical thing that makes pipelines like tool | other-tool and redirects like > file work. If you mix everything into one stream, the user will not be able to separate the “result” from “oops, something went wrong”.
Imagine that your program can output a list of tasks, and the user does this:
todo list > tasks.txt
They expect tasks.txt to contain only the list of tasks. If you also print warning: config not found or usage: ... there, the file becomes garbage. And the worst part: your program seems to “work”, but the scripts around it break.
At the level of the Go standard library, this is expressed directly in the API: os.Stdout and os.Stderr are different values. In CLI utilities, this historical separation is important: stdout is the “product of the command”, stderr is “diagnostics and hints”.
2. What to print to stdout and what to print to stderr
While you are learning, it is useful to keep a simple rule in mind: if it is data that can be processed further, print it to stdout; if it is a message for a person about a problem or a hint, print it to stderr.
To avoid turning this into a debate about “is this message really data or not?”, you can rely on common sense: imagine that the user redirected stdout to a file or another program. Would you want this message to end up inside the file? If not, then it belongs in stderr.
Below is a small table that usually answers 95% of the questions:
| What we print | Where | Why |
|---|---|---|
| Command result (list, calculations, JSON, table) | |
This is the command’s “product” |
| Errors (invalid arguments, failed to open file) | |
This is diagnostics; it should not corrupt the result |
|
|
This is a hint/diagnostics, not data |
| Progress, warnings | |
So that stdout stays clean |
| Debug fmt.Println("debug") | |
So you do not accidentally “break” the output |
Pay attention: I wrote about usage “in our course”. In the real world there are variations, but here we fix a simple and predictable rule: print usage to stderr, so it does not mix with data.
3. How to print to the right stream in Go
If you print with fmt.Println, you print to the “default” stream (usually stdout). For a disciplined CLI, we need to print explicitly.
In Go, this is done straightforwardly: the family of functions fmt.Fprint/fmt.Fprintln/fmt.Fprintf takes as its first argument “where to print” — that is, an io.Writer (in our case os.Stdout or os.Stderr).
Mini example: result in stdout, error in stderr
Now comes one of those moments when you add two lines to a program — and suddenly become “the person who writes proper CLI tools”. The example below is intentionally tiny, so you can see the idea without drowning in logic.
package main
import (
"fmt"
"os"
)
func main() {
fmt.Fprintln(os.Stdout, "result: OK") // result: OK
fmt.Fprintln(os.Stderr, "warning: something") // warning: something
}
If you run the program in the terminal, you will see both lines. But then the magic for automation starts: the user can redirect stdout separately from stderr.
4. Clean usage in Go via flag
usage (or “how to use” help) is a short text that explains how to run the program: which flags exist, which arguments are needed, which values are allowed. Ideally, usage helps the user fix an error in one attempt, instead of playing “guess what the author meant”.
The most common beginner mistake is to write usage manually once, and then change the flags and forget to update the help. As a result, the program says unknown flag -p, while usage still promises -p. The user starts suspecting a conspiracy. And, honestly, they are right.
In Go, the flag package is specifically designed to avoid duplicating information. Each flag has a name, a default, and a description — and from that you can print the list of flags automatically. So a good usage is usually a “header” + flag.PrintDefaults().
flag.Usage and flag.PrintDefaults()
The flag package has a variable called flag.Usage. This is a function that the package calls when it needs to show usage. By default it already prints something, but usually we want a clearer and more stable format — and we want to control the stream (almost always stderr).
Example: minimal usage for todo
Let’s agree on this: we are making a small CLI application called todo, which currently accepts -title (required) and -priority (optional). No subcommands and no complex architecture — only what we need for the topic of stdout/stderr/usage.
package main
import (
"flag"
"fmt"
"os"
)
func main() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: %s -title <text> [-priority <n>]\n", os.Args[0])
flag.PrintDefaults()
}
_ = flag.String("title", "", "task title (required)")
_ = flag.Int("priority", 1, "priority 1..5")
flag.Parse()
}
Notice three things.
- We print usage to os.Stderr, because it is a hint/diagnostics.
- We use os.Args[0] so that the usage shows the program name “as it was launched”.
- We do not print the flag list by hand — flag.PrintDefaults() does it for us.
Message order on error
One of the most annoying things in CLI tools is when the program just dumps usage without explaining what is actually wrong. The user sees a wall of text and does not understand what to fix: wrong flag? forgot an argument? number out of range? wrong string format?
Good UX for basic input errors is usually this: one short line saying “what is wrong”, then, optionally, a blank line, and then usage.
Important point: we are not discussing exit codes here (that will be a separate topic). So in the example below, we simply return from main.
Example: required -title and usage on error
The code becomes a couple of lines longer, but this is exactly the skeleton you will later copy from project to project.
package main
import (
"flag"
"fmt"
"os"
)
func main() {
title := flag.String("title", "", "task title (required)")
flag.Parse()
if *title == "" {
fmt.Fprintln(os.Stderr, "error: missing -title")
flag.Usage()
return
}
fmt.Fprintln(os.Stdout, "added:", *title) // added: Buy milk
}
Here the result (added: ...) goes to stdout, while the error and usage go to stderr. And that is exactly “the right way” for a basic CLI.
Why we print usage to stderr
Sometimes a philosophical question comes up: “But if the user invoked -h, that is not an error, so why stderr?” In different tools around the world, it varies, and in some cases help is indeed printed to stdout.
But at the start of the course, something else matters more to us: predictability and a “clean stdout”. If stdout always contains only command data, then anyone can safely do todo ... > out.txt and not fear that help will suddenly land there.
Besides, the hint is text for the user, not data for processing. And stderr is exactly intended for “messages about what is happening” (errors, warnings, explanations).
So in this course, the rule is: print usage/help to stderr. Even if in the future you decide to do it differently, you will do it consciously, not by accident.
Where the flag package prints its errors
The flag package can complain on its own if you pass an unknown flag or an invalid value. For example, -priority=abc for Int is a parsing error. And here it is important to understand that some messages may be printed by flag itself (before your code even reaches the semantic validation).
In the basic version, this is normal: flag prints its messages to the standard error stream. When you override flag.Usage, you at least make the help consistent.
5. Control flow and an example
It is useful to see the “picture” so that the brain stops treating this as a collection of random Fprintlns. When the user launches a CLI, you almost always have two branches: everything is fine — print data; something is wrong — print diagnostics.
Mini diagram
flowchart TD
A[Program start] --> B[Parse args / flag.Parse]
B --> C{Validation passed?}
C -->|yes| D[Print result to stdout]
C -->|no| E[Print reason to stderr]
E --> F[Print usage to stderr]
The idea is simple: stdout stays “clean” and contains only the result of the successful scenario.
Mini example: adding a task
Let’s put together a small but complete example. It is not “perfect” and not “architectural”, but it shows stream discipline and usage printing.
package main
import (
"flag"
"fmt"
"os"
)
func main() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: %s -title <text> [-priority 1..5]\n", os.Args[0])
flag.PrintDefaults()
}
title := flag.String("title", "", "task title (required)")
priority := flag.Int("priority", 1, "priority 1..5")
flag.Parse()
if *title == "" {
fmt.Fprintln(os.Stderr, "error: missing -title")
flag.Usage()
return
}
if *priority < 1 || *priority > 5 {
fmt.Fprintln(os.Stderr, "error: -priority must be in range 1..5")
flag.Usage()
return
}
fmt.Fprintf(os.Stdout, "added: %s (p=%d)\n", *title, *priority) // added: Buy milk (p=2)
}
What matters here is precisely the discipline: errors and help do not pollute the result.
6. Typical mistakes
Mistake #1: printing errors with fmt.Println, that is, to stdout.
This happens out of habit: you are already used to fmt.Println, and your hand automatically writes it everywhere. As a result, the user redirects the output to a file, and there end up error: ... and Usage: .... The fix is simple: print all errors and hints with fmt.Fprintln(os.Stderr, ...), and data with os.Stdout.
Mistake #2: printing usage without a specific reason.
When the program just prints help and silently finishes, the user does not understand what exactly they did wrong. Good style is to explain the reason first in one line (for example, missing -title or -priority must be in range 1..5), and only then show usage.
Mistake #3: writing usage by hand and forgetting to update it when flags change.
Today you have -priority, tomorrow you renamed it to -p, but the usage stayed old. The user sees a contradiction and starts doubting reality. The solution is to use flag.PrintDefaults(): then the list of flags in the help automatically matches the declarations in the code.
Mistake #4: mixing normal output and hints.
When in one place you print Error: ..., in another ERROR - ..., and in a third usage: without a capital letter, it feels as if the program were written by three people and one cat. Choose one consistent style: for example, error: ... (lowercase) and then Usage: .... Even in a small utility, this makes the interface calmer.
Mistake #5: hardcoding the program name in usage.
If you write Usage: todo ..., and later the binary is called something else (or the user runs ./todo), the help looks strange. Better to use os.Args[0]: then usage shows the name exactly as it is actually launched, and that confuses people less.
GO TO FULL VERSION