Command-Line Arguments in Golang

To get the command-line arguments in Go, you can use the “os.Args” variable. The os.Args variable is a slice of strings that contains the command line arguments passed to the program.

The first argument in the slice is the program’s name, and the remaining arguments are the values passed to the program. The os.Args[1:] represent other arguments in our program. Individual arguments are addressed through indexing.

For example, if you start the following program with the command mainprogram arg1 arg2, the Args variable will contain the following values:

[mainprogram arg1 arg2]

Using normal indexing, you can access individual arguments in the “Args” slice. For example, the following code will print the second argument:

fmt.Println(os.Args[1])

You can also use the “len()” function to get the number of arguments passed to the program.

Example

package main

import (
  "fmt"
  "os"
)

func main() {
  fmt.Println("Number of arguments:", len(os.Args))
  for _, arg := range os.Args {
    fmt.Println(arg)
  }
}

Output

go run service.go hello world
Number of arguments: 3
/var/folders/8v/x42znv0n7r5383bnmngj4kmw0000gn/T/go-build3574042695/b001/exe/service
hello
world

That’s pretty much it.

Leave a Comment