Reading Arguments from the Command-Line
This lesson explains two packages of Go that let us read arguments from the command line.
With the os
package
The package os
also has a variable os.Args
of type slice of strings that can be used for elementary command-line argument processing, which is reading arguments that are given on the command-line when the program is started. Look at the following greetings-program:
package main import ( "fmt" "os" "strings" ) func main() { who := "Alice " if len(os.Args) > 1 { who += strings.Join(os.Args[1:], " ") } fmt.Println("Good Morning", who) }
When we run this program, the output is: Good Morning Alice. The same output we get when we run it on the command-line as:
go run main.go
But, when we give arguments on the command-line like:
go run main.go John Bill Marc Luke
we get Good Morning Alice John Bill Marc Luke as an output.
When there is at least one command-line argument, the slice os.Args[]
takes in the arguments (separated by a space), starting from index 1 since os.Args[0]
contains the name of the program, os_args ...