How to get command-line input in Go

Command-line arguments are used to provide arguments/parameters to the program when it is invoked. They are provided to the program as slice of arguments, where the first element is the path to the program file, and the following elements contain the user-provided arguments.

Command-line arguments in Go are stored in the os.Args variable accessed from the os module.

Syntax

args = os.Args

Code

Run the command go run command_line.go hello world!.

package main
import (
  "fmt"
  "os"
)
func main() {
  args := os.Args
  
	for i := 0; i < len(args); i++ {
		fmt.Println(args[i])
	}
}

Output

widget

The code above prints the command-line arguments provided to the Go script. The program takes the command-line arguments “Hello world!” and prints them to the terminal.

As we can see, the first printed argument is the file path of our program, and the subsequent arguments are printed after.