A command-line argument is a value supplied when a program starts from a terminal or operating-system process launcher. In Go, the runtime stores these values in os.Args, whose first element is the command itself; application arguments begin at os.Args[1]. section 2.7.1
Use arguments to make a program operate on caller-selected values:
- Check len(os.Args) before indexing so a missing required argument produces a clear error instead of an invalid access. section 2.7
- Read the selected value from os.Args[1] and pass it to the operation, such as os.ReadFile. section 2.7.1
- Use the flag package when options need names, types, defaults, help, or parsing; retrieve remaining positional arguments with flag.Args(). section 10.2
Selecting a file at startup
A word-counting program can accept any filename instead of being tied to words.txt. It checks for an argument, reads os.Args[1], splits the contents into fields, and prints the word count. A richer CLI can instead parse flags and require input and output filenames as positional arguments. section 2.7 section 10.2
Listing 2.30 Altering main.go to take a filename as an argument
package main
import (
"fmt"
"log"
"os"
"strings"
)
func main() {
if len(os.Args) < 2 {
log.Println("need to provide filename!")
os.Exit(1)
}
fileContents, err := os.ReadFile(os.Args[1])
if err != nil {
log.Println(err)
os.Exit(1)
}
words := strings.Fields(string(fileContents))
fmt.Println("Found", len(words), "words")
}
Runnable Go listing showing argument validation, filename selection, file reading, and error handling. section 2.7













