Welcome to our deep dive into Go's os.Args! This lesson will guide you through working with the command line arguments in Go, making your programs more versatile and powerful.
os.Args is a built-in slice in Go that contains command-line arguments passed to a Go program when it runs.
š Note: The first element, os.Args[0], always contains the name of the program itself.
To work with os.Args, simply import the os package at the beginning of your Go program. Here's a basic example:
package main
import (
"fmt"
"os"
)
func main() {
for _, arg := range os.Args {
fmt.Println(arg)
}
}šÆ Run this program by saving it as main.go and running go run main.go followed by any arguments you'd like to pass. For example:
go run main.go Hello WorldThe output will display the program name and the arguments you provided:
./main
Hello
World
What if we want to pass a variable number of arguments? Let's create a simple command-line calculator.
package main
import (
"fmt"
"os"
"strconv"
"strings"
)
func main() {
if len(os.Args) < 4 {
fmt.Println("Usage: go run calc.go ADD|SUBTRACT number1 number2")
return
}
operator := os.Args[1]
num1, err := strconv.ParseFloat(os.Args[2], 64)
if err != nil {
fmt.Println("Error:", err)
return
}
num2, err := strconv.ParseFloat(os.Args[3], 64)
if err != nil {
fmt.Println("Error:", err)
return
}
var result float64
switch operator {
case "ADD":
result = num1 + num2
case "SUBTRACT":
result = num1 - num2
default:
fmt.Println("Invalid operator. Use ADD or SUBTRACT.")
return
}
fmt.Printf("%.2f %s %.2f = %.2f\n", num1, operator, num2, result)
}Now you can run this program like:
go run calc.go ADD 5 3The output will be:
5.00 ADD 3.00 = 8.00
What is `os.Args` in Go?
With this foundation, you're ready to explore more complex command-line tools and scripts in Go! Keep learning, keep coding, and enjoy your programming journey! š