← Back to Go Course | Chapter 13: File IO & OS | Lesson 7 of 7

Command-Line Arguments

Command-line arguments are extra instructions you type after a program's name, like telling a delivery driver an address right when you send them off.

Reading os.Args

os.Args is a slice of strings containing the command that launched the program: its own name at index 0, followed by each argument the user typed after it.

Example: Reading os.Args

markup
package main

import (
	"fmt"
	"os"
)

func main() {
	fmt.Println("number of args (including program name):", len(os.Args))
	fmt.Println("program name:", os.Args[0])
}

Safely Accessing Arguments

Because os.Args might be shorter than expected if the user forgot an argument, code should check its length before indexing into it, to avoid a runtime panic.

Note: Always check len(os.Args) before indexing past position 0.

Example: Safely Accessing Arguments

markup
package main

import (
	"fmt"
	"os"
)

func main() {
	if len(os.Args) < 2 {
		fmt.Println("no extra arguments provided")
		return
	}
	fmt.Println("first argument:", os.Args[1])
}

Parsing Flags with the flag Package

For structured, named command-line options (rather than raw positional arguments), the standard library's flag package parses things like -name=value automatically, including type conversion and default values.

Example: Parsing Flags with the flag Package

markup
package main

import (
	"flag"
	"fmt"
)

func main() {
	name := flag.String("name", "World", "name to greet")
	flag.Parse()
	fmt.Printf("Hello, %s!\n", *name)
}
Common Mistakes
  1. Forgetting os.Args[0] is always the program's own name, not the first real argument -- real arguments start at index 1.
  2. Indexing into os.Args without first checking len(os.Args), causing an index-out-of-range panic when an expected argument is missing.
  3. Reaching for manual os.Args parsing for complex flag handling instead of using the standard library's flag package.
Chapter Summary
  • os.Args is a []string holding the program name followed by every command-line argument passed to it.
  • Real arguments start at index 1; os.Args[0] is always the executable's own name/path.
  • Always check len(os.Args) before indexing, to avoid a panic when expected arguments are missing.
  • The flag package provides structured parsing for named flags like --verbose or -port=8080.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.