Command-Line Arguments
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
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])
}
Login to try C/C++/Java/PHP code in the editor
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
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])
}
Login to try C/C++/Java/PHP code in the editor
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
package main
import (
"flag"
"fmt"
)
func main() {
name := flag.String("name", "World", "name to greet")
flag.Parse()
fmt.Printf("Hello, %s!\n", *name)
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting os.Args[0] is always the program's own name, not the first real argument -- real arguments start at index 1.
- Indexing into os.Args without first checking len(os.Args), causing an index-out-of-range panic when an expected argument is missing.
- Reaching for manual os.Args parsing for complex flag handling instead of using the standard library's flag package.
- 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: