Go os.Args (Command Line)

beginner
19 min

Go os.Args (Command Line)

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.

Understanding os.Args

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.

Accessing Command-Line Arguments

To work with os.Args, simply import the os package at the beginning of your Go program. Here's a basic example:

go
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:

sh
go run main.go Hello World

The output will display the program name and the arguments you provided:

./main Hello World

Handling Variable Number of Arguments

What if we want to pass a variable number of arguments? Let's create a simple command-line calculator.

go
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:

sh
go run calc.go ADD 5 3

The output will be:

5.00 ADD 3.00 = 8.00

Quiz Time!

Quick Quiz
Question 1 of 1

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! 🌟