How to Use flag Package for CLI Arguments in Go

Cli
Use the flag package to define variables and call flag.Parse() to read command-line arguments in Go.

Use the flag package to define variables that correspond to command-line arguments, then call flag.Parse() to populate them.

package main

import (
	"flag"
	"fmt"
)

func main() {
	var name string
	var count int

	flag.StringVar(&name, "name", "world", "A greeting name")
	flag.IntVar(&count, "count", 1, "Number of greetings")

	flag.Parse()

	for i := 0; i < count; i++ {
		fmt.Printf("Hello, %s!\n", name)
	}
}

Run with go run main.go -name=alice -count=3.