In this tutorial, we will learn how to handle command-line arguments in Go programming language. Command-line arguments are parameters provided to a program when it is invoked. They are common in programming to provide flexibility and control to the user.
By the end of this tutorial, you'd be able to write programs that accept and utilize command-line arguments.
In Go, command-line arguments are accessed using the os.Args
variable in the os
package. This variable is a slice of strings, where each string is an argument provided to the program.
The first element in this slice, os.Args[0]
, is the name of the program itself. The actual command-line arguments start from os.Args[1]
.
os.Args
before accessing its elements to avoid "index out of range" errors.flag
package can simplify command-line argument parsing.package main
import (
"fmt"
"os"
)
func main() {
// Print the name of the program
fmt.Println("Program:", os.Args[0])
// Print the command-line arguments
for i, arg := range os.Args[1:] {
fmt.Printf("arg %d: %s\n", i+1, arg)
}
}
In this program, we first print the name of the program, which is os.Args[0]
. Then we print each command-line argument. If you run this program with arguments, you will see them printed out.
package main
import (
"fmt"
"os"
)
func main() {
if len(os.Args) < 2 {
fmt.Println("No arguments provided.")
} else {
fmt.Println("Arguments:", os.Args[1:])
}
}
In this program, we first check if any arguments were provided. If not, we print a message. Otherwise, we print the arguments.
In this tutorial, we learned how to handle command-line arguments in Go. We learned that os.Args
is a slice that contains the arguments, starting with the program name at index 0.
For further learning, you can explore the flag
package in Go which provides more advanced command-line argument parsing.
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println(len(os.Args) - 1)
}
This program prints the number of arguments by printing the length of os.Args
minus one (to exclude the program name).
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
if len(os.Args) < 2 {
fmt.Println("Please provide a number.")
return
}
num, err := strconv.Atoi(os.Args[1])
if err != nil {
fmt.Println("Invalid number.")
return
}
fmt.Println(num * num)
}
This program converts the first argument to an integer and squares it. If no argument is provided, or if the argument is not a valid number, it prints an error message.
package main
import (
"fmt"
"os"
)
func main() {
for i := len(os.Args) - 1; i > 0; i-- {
fmt.Println(os.Args[i])
}
}
This program prints the arguments in reverse order by iterating over os.Args
in reverse.