Table of Contents
Introduction
In this tutorial, we will explore how to work with command-line arguments in Go. Command-line arguments provide a convenient way to pass inputs to a Go program when executing it from the command line. By the end of this tutorial, you will understand how to retrieve and process command-line arguments in your Go scripts or programs.
Prerequisites
To follow along with this tutorial, you should have basic knowledge of the Go programming language and have Go installed on your system. If you don’t have Go installed, visit the official Go website (https://golang.org) and download the appropriate version for your operating system.
Getting Started
Before we dive into command-line arguments, let’s start by creating a simple Go script. Open your preferred text editor and create a new file called main.go
. To keep things simple, we will write our code in a single file.
Inside main.go
, add the following code:
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("Hello, World!")
}
Save the file and exit the text editor. Now, open a terminal or command prompt and navigate to the directory where you saved main.go
. To compile and run the Go script, use the following command:
go run main.go
If everything is set up correctly, you should see the output Hello, World!
printed in the terminal.
Command-Line Arguments
Command-line arguments are strings passed to a program when it is executed. These arguments provide additional information or inputs to the program. In Go, we can access the command-line arguments through the os
package, specifically the os.Args
variable.
The os.Args
variable is a slice of strings that contains all the command-line arguments passed to the program. The first element (os.Args[0]
) is the name or path of the program itself, and the following elements are the arguments provided.
To access the command-line arguments, we can simply use os.Args
in our Go code. Let’s modify our main.go
script to print out the command-line arguments:
package main
import (
"fmt"
"os"
)
func main() {
args := os.Args
fmt.Println("Command-Line Arguments:")
for _, arg := range args {
fmt.Println(arg)
}
}
Save the file, and in the terminal, run the following command:
go run main.go argument1 argument2 argument3
You should see the following output:
Command-Line Arguments:
/path/to/main.go
argument1
argument2
argument3
As you can see, the os.Args
slice includes the path to the Go script as the first element, followed by the provided arguments.
Examples
Example 1: Calculating Sum
Let’s create an example that takes two command-line arguments as numbers and calculates their sum.
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
args := os.Args
if len(args) != 3 {
fmt.Println("Invalid number of arguments. Please provide two numbers.")
return
}
num1, err1 := strconv.Atoi(args[1])
num2, err2 := strconv.Atoi(args[2])
if err1 != nil || err2 != nil {
fmt.Println("Invalid numbers provided.")
return
}
sum := num1 + num2
fmt.Printf("Sum: %d\n", sum)
}
Save the file as sum.go
and in the terminal, run the following command:
go run sum.go 10 20
The output should be:
Sum: 30
Example 2: File Reader
In this example, we will create a command-line script that reads and prints the contents of a file specified as a command-line argument.
package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
args := os.Args
if len(args) != 2 {
fmt.Println("Invalid number of arguments. Please provide a filename.")
return
}
filename := args[1]
data, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Println("Error reading file:", err)
return
}
fmt.Println("File Contents:")
fmt.Println(string(data))
}
Save the file as file_reader.go
and create a sample text file called sample.txt
in the same directory. Add some content to the sample.txt
file.
In the terminal, run the following command:
go run file_reader.go sample.txt
You should see the contents of the sample.txt
file printed in the terminal.
Conclusion
In this tutorial, we learned how to work with command-line arguments in Go. We explored the os.Args
variable to access the command-line arguments and demonstrated two examples: calculating the sum of two numbers and reading the contents of a file. Remember to handle the cases when the user provides invalid or insufficient arguments to ensure your program behaves as expected. Command-line arguments provide a flexible way to interact with your Go programs and can be used to configure behavior, pass inputs, or provide necessary information from the command line.