標籤:short fun 結果 例子 UI [] 用法 參數 tween
flag包
實現了命令列的flag解析
用法
func String(name string, value string, usage string) *string
String 定義了一個指定名字為name的string類型flag,預設值為value,用法usage.傳回值是string類型的地址,存放了flage對應的值
func StringVar(p *string, name string, value string, usage string)
StringVar 定義了指定名字為name的string類型的flage,預設值為value,用法為usage.參數p指標指向存在flag值的空間.
func Var(value Value, name string, usage string)
Var 定義了指定名字name和用法的flag.第一個入參為flag的值,類型為Value,可以存放使用者自訂實現的Value.舉個例子,使用者可以建立一個flag,傳入參數用逗號分割,放入一個切片裡.
- func Args() []string
Args 返回沒有flag的命令列參數.
執行個體1
package mainimport ( "errors" "flag" "fmt" "strings" "time")var species = flag.String("species", "gopher", "the species we are studying")var gopherType stringvar gopherType1 stringvar intervalFlag intervalfunc init() { const ( defaultGopher = "pocket" usage = "the variety of gopher" ) flag.StringVar(&gopherType, "gopher_type", defaultGopher, usage) flag.StringVar(&gopherType1, "g", defaultGopher, usage+" (shorthand)") flag.Var(&intervalFlag, "deltaT", "comma-separated list of intervals to use between events")}type interval []time.Durationfunc (i *interval) String() string { return fmt.Sprint(*i)}func (i *interval) Set(value string) error { if len(*i) > 0 { return errors.New("interval flag already set") } for _, dt := range strings.Split(value, ",") { duration, err := time.ParseDuration(dt) if err != nil { return err } *i = append(*i, duration) } return nil}func main() { flag.Parse() fmt.Println("species:", *species) fmt.Println("gopherType:", gopherType) fmt.Println("gopherType1:", gopherType1) fmt.Println("intervalFlag:", intervalFlag)}
編譯運行
go build flag.go ./flag -species dog -g chicken -gopher_type bird -deltaT 10s,15s,1m,1h
運行結果
species: doggopherType: birdgopherType1: chickenintervalFlag: [10s 15s 1m0s 1h0m0s]
執行個體2
package mainimport ( "fmt" "flag")func main() { flag.Parse() args := flag.Args() for index, val := range args { fmt.Printf("arg%v: %v \n", index, val) } return}
運行結果
arg0: 123 arg1: 123 arg2: 345 arg3: 678
執行個體3
package mainimport ( "fmt" "os")func main() { for index, val := range os.Args { fmt.Printf("arg%v: %v \n", index, val) } return}
運行結果
arg0: ./flag2arg1: 123 arg2: 123 arg3: 345 arg4: 678
Go語言-flag使用