Reading Arguments from the Command-Line
Explore how to handle command-line arguments in Go using the os package for simple argument reading and the flag package for parsing flags and options. Understand how to use flags to customize program behavior, test boolean flags, and process arguments effectively to build flexible Go applications.
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 in this case.
At line 10, we test if there is more than one command-line argument with len(os.args) > 1. In that case, all the remaining arguments given ...