标签: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,传入参数用逗号分割,放入一个切片里.
package main
import (
"errors"
"flag"
"fmt"
"strings"
"time"
)
var species = flag.String("species", "gopher", "the species we are studying")
var gopherType string
var gopherType1 string
var intervalFlag interval
func 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.Duration
func (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: dog
gopherType: bird
gopherType1: chicken
intervalFlag: [10s 15s 1m0s 1h0m0s]
package main
import (
"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
package main
import (
"fmt"
"os"
)
func main() {
for index, val := range os.Args {
fmt.Printf("arg%v: %v \n", index, val)
}
return
}
运行结果
arg0: ./flag2
arg1: 123
arg2: 123
arg3: 345
arg4: 678
标签:short fun 结果 例子 UI [] 用法 参数 tween
原文地址:http://blog.51cto.com/12880687/2130167