Understanding Command-Line Arguments
Command-line input is a fundamental way for users to interact with command-line interface (CLI) applications. In Golang, command-line arguments are passed to the program when it is executed and can be accessed through the os.Args
slice.
Basic Argument Retrieval
Here's a simple example of how to access command-line arguments:
package main
import (
"fmt"
"os"
)
func main() {
// os.Args[0] is the program name itself
// os.Args[1:] contains the actual arguments
args := os.Args[1:]
fmt.Println("Number of arguments:", len(args))
for i, arg := range args {
fmt.Printf("Argument %d: %s\n", i, arg)
}
}
Argument Types and Parsing
Command-line arguments are typically passed as strings. For different types of inputs, you'll need to parse them:
graph TD
A[Raw String Arguments] --> B{Parse to Desired Type}
B --> |Integer| C[strconv.Atoi()]
B --> |Float| D[strconv.ParseFloat()]
B --> |Boolean| E[strconv.ParseBool()]
Common Argument Patterns
Pattern |
Description |
Example |
Simple Flags |
Single character or word flags |
-h , --help |
Key-Value Pairs |
Arguments with associated values |
--name=John |
Positional Arguments |
Arguments based on their position |
./program input.txt output.txt |
Using the flag
Package
Golang's standard library provides a more robust way to handle command-line arguments:
package main
import (
"flag"
"fmt"
)
func main() {
// Define flags
name := flag.String("name", "Guest", "Your name")
age := flag.Int("age", 0, "Your age")
// Parse the flags
flag.Parse()
fmt.Printf("Name: %s, Age: %d\n", *name, *age)
}
Best Practices
- Always validate and sanitize input
- Provide clear usage instructions
- Handle potential parsing errors
- Use meaningful flag names
Error Handling Considerations
When working with CLI inputs, always anticipate and handle potential errors:
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
if len(os.Args) < 2 {
fmt.Println("Usage: program <number>")
os.Exit(1)
}
num, err := strconv.Atoi(os.Args[1])
if err != nil {
fmt.Println("Invalid input. Please provide a number.")
os.Exit(1)
}
fmt.Println("Parsed number:", num)
}
Tip: When developing CLI applications on LabEx, always test your input validation thoroughly to ensure robust and user-friendly interfaces.