What are command-line arguments in Golang

What are command-line arguments in Go?

Like any other programming language belonging to the C language family, Go language has the built-in power to handle command-line arguments.

To access all command-line arguments in their raw format, we need to use Args variables imported from the os package. This type of variable is a string ([]) slice. Args is an argument that starts with the name of the program in the command-line. The first value in the Args slice is the name of our program, while os.Args [1:] denotes other arguments in our program. Individual arguments are addressed through indexing.

package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("len", len(os.Args))
for _, arg := range os.Args[1:] {
fmt.Println(arg)
}
}

os.Args[0] stands for program name, len(os.Args) gives us the length of the slice, and os.Args[1:] results in a slice without the name of the program. Running the code above with none arguments yields len 1,which stands for our program name. If we run the same program with some arguments:

$ go run main.go Shuaib M bot 22 little

Our results/outputs are going to be:

len 6 

Shuaib 

M 

bot 

22 

little

How to parse command-line arguments in Go

The Go language has a package called flag to parse command-line arguments for us. The packageflag allows for some flexibility.

Flag declarations are available for string, integer, and boolean. Once we have declared our flags, we call flag.Parse() to execute the command-line parsing. The code base below illustrates this further:

package main
import (
"flag"
"fmt"
)
func main() {
num := flag.Int("value", 2, "looping through")
flag.Parse()
value := *num
i := 0
for i < value {
fmt.Println("GO")
i++
}
}

Flag generally takes in three parameters:

  • the flag name
  • default value
  • help line

These are shown in the program above as value 2 and looping through, respectively. Dereferencing is key in accessing any type of flag in Golang, which is what we try to achieve on line 12.

As we can see from the simple program above, $ go run main.go prints GO twice for us. This is the default number set in our flag on line 9. We can specify the number of times we want the printing to occur using $ go run main.go -value 7, where 7 is our specified value.

$ go run main.go -value 7 simply tells the program that we want GO to be printed 7 times. We can use -h or --help flags to automatically generate help text for our command-line program.

NOTE: If we provide a flag that wasn’t specified, the program will print an error message and show the help text to guide us. If we omit flags, they automatically take their default values.

Conclusion

In this shot we have worked through the basic syntax and applications of command line argument in go language. Command-line arguments are intended to easily add instructions into our program during runtime.

Free Resources