Go Standard Library Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

  1. Open the console and create the folder chapter01/recipe02.
  2. Navigate to the directory.
  3. Create the main.go file with the following content:
        package main
import (
"fmt"
"os"
)

func main() {

args := os.Args

// This call will print
// all command line arguments.
fmt.Println(args)

// The first argument, zero item from slice,
// is the name of the called binary.
programName := args[0]
fmt.Printf("The binary name is: %s \n", programName)

// The rest of the arguments could be obtained
// by omitting the first argument.
otherArgs := args[1:]
fmt.Println(otherArgs)

for idx, arg := range otherArgs {
fmt.Printf("Arg %d = %s \n", idx, arg)
          }
}
  1. Build the binary by executing go build -o test.
  2. Execute the command ./test arg1 arg2(Windows users can run test.exe arg1 arg2).
  3. See the output in the Terminal: