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:


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


package main

import (

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


go run service.go hello world
Number of arguments: 3

That’s pretty much it.

Leave a Comment