以bool解析为例子:
func main() {
var block bool
//如果有-b参数则为真,否则为假
//使用./flag -b=false
//./flag -b=ture
flag.BoolVar(&block, "b", false, "set for block")
flag.Parse()
fmt.Println("falg", block)
}
通过flag.NewFlagSet创建flagset.使用返回的set注册标志,调用set.Parse(argv)解析命令行. argv为字符串数组
实现代码如下:
package main
import (
"errors"
"flag"
"fmt"
"strings"
"time"
)
//自定义结构实现接口
type args []string
func (a *args) String() string {
return fmt.Sprintf("%v", *a)
}
func (i *args) Set(value string) error {
if len(*i) > 0 {
return errors.New("interval flag already set")
}
for _, dt := range strings.Split(value, ",") {
*i = append(*i, dt)
}
return nil
}
func base_parse() {
const (
defaultGopher = "pocket"
usage = "the variety of gopher"
)
var log int
//init for init param, return int point
// param:name, deaault val, help message
//解析参数通过指针返回
var intflag = flag.Int("int", 100, "help message for int")
flag.StringVar(&gopherType, "gopher_type", defaultGopher, usage)
flag.StringVar(&gopherType, "g", defaultGopher, usage+"(shorthand)")
//指定一个传入参数的指针
flag.IntVar(&log, "log_level", 0, "log level")
flag.Parse()
fmt.Println("initFlag:", *intflag)
fmt.Println("log_level:", log)
fmt.Println("gopherType string ", gopherType)
}
/*自定义参数解析*/
func userdef_parse() {
var argFlag args
flag.Var(&intervalFlag, "deltaT", "comma-separated list of intervals to use between events")
flag.Var(&argFlag, "arg", "comma-separated list of intervals to use between events")
flag.Parse()
fmt.Println("arg string ", argFlag)
fmt.Println(intervalFlag)
}
/*解析传入的字符串*/
func parse_input(arg string) {
argv := []string{}
for _, dt := range strings.Split(arg, " ") {
argv = append(argv, dt)
}
//创建flagSet
set := flag.NewFlagSet("test", flag.ExitOnError)
//注册解析参数
varflag := set.String("ver", "myver", "version")
pflag := set.String("p", "myp", "version")
//解析参数
set.Parse(argv)
fmt.Println("input parse:", *varflag, *pflag)
}
func main() {
userdef_parse()
parse_input("-p 123 -ver 1234")
}