The Go language USES the flag package for parameter resolution on the command line

  • 2020-06-01 10:00:17
  • OfStack

flag is a package that parses command-line arguments provided by the Go standard library.


flag.Type(name, defValue, usage)

Type is String, Int, Bool, etc. And returns a pointer of the corresponding type.

flag.TypeVar(&flagvar, name, defValue, usage)

Bind flag to a variable.

Custom flag
As long as the flag. Value interface is implemented:

type Value interface {
  String() string
  Set(string) error

The flag is defined as follows:

flag.Var(&flagvar, name, usage)

The sample

package main
import "flag"
import "fmt"
import "strconv"
type percentage float32
func (p *percentage) Set(s string) error {
  v, err := strconv.ParseFloat(s, 32)
  *p = percentage(v)
  return err
func (p *percentage) String() string { return fmt.Sprintf("%f", *p) }
func main() {
  namePtr := flag.String("name", "lyh", "user's name")
  agePtr := flag.Int("age", 22, "user's age")
  vipPtr := flag.Bool("vip", true, "is a vip user")
  var email string
  flag.StringVar(&email, "email", "", "user's email")
  var pop percentage
  flag.Var(&pop, "pop", "popularity")
  others := flag.Args()
  fmt.Println("name:", *namePtr)
  fmt.Println("age:", *agePtr)
  fmt.Println("vip:", *vipPtr)
  fmt.Println("pop:", pop)
  fmt.Println("email:", email)
  fmt.Println("other:", others)

$ ./command-line-flags
name: lyh
age: 22
vip: true
other: []

$ ./command-line-flags -name golang -age 4 -vip=true -pop 99  concise   High concurrency   , etc. 
name: golang
age: 4
vip: true
pop: 99
other: [ concise   High concurrency   , etc. ]

$ ./command-line-flags -h
Usage of ./command-line-flags:
 -age=22: user's age
 -email="": user's email
 -name="lyh": user's name
 -pop=0.0: popularity
 -vip=true: is a vip user

Related articles: