Golang flag package

Golang flag

flag 是 go 标准库提供的解析命令行参数的包。
  1. flag use style

    • flag.Type(name, defvalue, usage)

        其中 Type: [String, Int, Bool ...], 并返回一个相应类型的指针。
      
    • 将 flag 绑定到一个变量上 : flag.TypeVar(&flagvar, name, defvalue, usage)

        其中 Type: [String, Int, Bool ...]
      
  2. Custom flag

    只要实现 flag.Value interface:

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

    flag.Var(&flagvar, name, usage) 方式定义此 flag

  3. Example

     package main 
     
     import (
         "flag"
         "fmt"
         "strconv"
     )
     
     const APP_VERSION = "0.1"
     
     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() {
         // *T
         namePtr := flag.String("name", "hl", "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", "hlGopen@doingsbook.com", "user`s email")
     //    p := &email
     //    fmt.Println(p)
     //    fmt.Println(*p)
         
         var pop percentage
         flag.Var(&pop, "pop", "popularity")
         
         flag.Parse() // Scan the arguments list 
         others := flag.Args()
         
         if *vipPtr {
             fmt.Println("Version:", APP_VERSION)
         }
         
         fmt.Println("name: ", *namePtr)
         fmt.Println("age: ", *agePtr)
         fmt.Println("pop: ", pop)
         fmt.Println("email: ", email)
         fmt.Println("others: ", others)
         
     }     
    
  • $ ./command-line-flags   
    Version: 0.1
    name:  hl
    age:  22
    pop:  0
    email:  hlGopen@doingsbook.com
    others:  []
    
  •  $ ./command-line-flags -name golang -age 20 -vip=false -pop 99 简洁 高并发 等等
     name:  golang
     age:  20
     pop:  99
     email:  hlGopen@doingsbook.com
     others:  [简洁 高并发 等等]
    
  •   $ ./command-line-flags -h
      Usage of command-line-flags:
        -age=22: user`s age
        -email="hlGopen@doingsbook.com": user`s email
        -name="hl": user`s name
        -pop=0.000000: popularity
        -vip=true: is a vip user

推荐阅读更多精彩内容