Go
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions and Methods
-
Section 4: Concurrency
-
Section 5: Packages and Tooling
-
Section 6: More Standard Library
-
Section 7: Building Services
-
Section 8: Advanced Go
-
Section 9: Go in the Cloud-Native Ecosystem
-
Section 10: Data Structures and Algorithms in Go
-
Section 11: Testing and Deployment
-
Section 12: Practical Projects
-
Section 13: More Standard Library Practice
-
Section 14: More Practice Projects
-
Section 15: Design Patterns in Go
-
Section 16: Interview Practice
-
Section 17: Package fmt In Depth
-
Section 18: Package strings and strconv
-
Section 19: Package os and io
-
Section 20: Package time
-
Section 21: Package sort and container
-
Section 22: Package encoding
-
Section 23: Package net/http In Depth
-
Section 24: Package context
-
Section 25: Package regexp and bytes
-
Section 26: Package errors In Depth
-
Section 27: Package crypto and hash
-
Section 28: Package flag and log
-
Section 29: Package sync In Depth
-
Section 30: More Practice Exercises
-
Section 31: Go Modules and Workspaces In Depth
-
Section 32: Generics Deep Dive (Go 1.18+)
-
Section 33: Testing Package In Depth
-
Section 34: More Interview and Whiteboard Practice
-
Section 35: Package math and unicode
-
Section 36: Package path and filepath
-
Section 37: Package database/sql
-
Section 38: Package text/template and html/template
-
Section 39: Package archive and compress
-
Section 40: Lower-Level net Package
-
Section 41: Package runtime and reflect
-
Section 42: Package embed and io/fs
-
Section 43: Go Assembly and CGO Basics
-
Section 44: Building CLIs and TUIs
-
Section 45: Go Performance Tuning
-
Section 46: More Real-World Projects
-
Section 47: Go in Production
-
Section 48: Go Design Patterns
-
Section 49: Go Interfaces Deep Dive
-
Section 50: Final Practice and Review
118: os.Args and Command-Line Arguments
I've seen this specific bug more times than I can count when developers start building their first CLI tools in Go. You're trying to pass a filename or a configuration path into your program, but for some reason, the program keeps trying to "open" its own binary file instead of the file you actually typed in the terminal.
package main
import (
"fmt"
"os"
)
func main() {
// We want to print the name of the file the user wants to process
fileName := os.Args[0]
fmt.Printf("Processing file: %s\n", fileName)
// Imagine some logic here to open and read the file...
}
If you run this with go run main.go data.txt, you'll see it prints something like Processing file: /tmp/go-build.../exe/main. It completely ignored data.txt. It's frustrating because the code looks logically sound—you're grabbing the first thing in the arguments list, right?
Why your program is trying to open itself
The "gotcha" here is that os.Args isn't just a list of the arguments you passed to the program. It's a slice of strings where the very first element—index 0—is always the path to the program that is currently running. Whether you're using go run or running a compiled binary, the operating system always puts the executable's name at the front of the line.
So, if you run mytool input.txt output.txt, the os.Args slice actually looks like this:
os.Args[0]:"mytool"os.Args[1]:"input.txt"os.Args[2]:"output.txt"
Indexing from one and guarding against panics
To fix this, you need to start looking at index 1. But there's a second trap: if you try to access os.Args[1] and the user didn't provide any arguments, your program will panic with an index out of range error. I hate it when my tools just crash without telling me why, so we should always check the length of the slice first.
package main
import (
"fmt"
"os"
)
func main() {
// Check if the user actually provided the required argument
if len(os.Args) < 2 {
fmt.Println("Usage: go run main.go [filename]")
os.Exit(1) // Exit with an error code
}
// Index 0 is the program name, index 1 is the first real argument
fileName := os.Args[1]
fmt.Printf("Processing file: %s\n", fileName)
}
Now the program behaves. It checks if there's enough data to proceed, provides a helpful usage message if not, and correctly identifies the user's input. If you need all the arguments minus the program name, a clean way to do that is by slicing the slice: args := os.Args[1:]. This gives you a new slice containing only the actual inputs.
As your tools get more complex—say, you need -v for verbose mode or -port 8080—you'll likely move over to the flag package. But os.Args is the raw, honest foundation of how Go sees the command line. It's fast, it's simple, and once you remember that index 0 is "the boss," it's very reliable.
📋 Practical Task
Build a Simple File Word Counter
Create a Go program that accepts a filename as a command-line argument. The program should:
- Check if a filename was provided via
os.Args. If not, print a usage message (e.g., "Please provide a filename") and exit the program. - Read the content of the provided file (you can use
os.ReadFile). - Count the number of words in that file (hint:
strings.Fieldsis very helpful here). - Print the total word count to the console.
Test your tool: Run it once without any arguments to ensure it doesn't panic, and then run it again with a path to a real .txt file to verify the count.
There are no comments for now.