go flagset用法

pflag用于子命令,比如下面示例程序:

package main

import (
	"flag"
	"fmt"
	"os"
)

type Options struct {
	Firstname string
	Lastname string
}
func main() {

	p:=&Options{Firstname: "oneslide"}
        p.InitOptions(flag.NewFlagSet("change",flag.ContinueOnError))

	fmt.Println(p)
}


func(o *Options) InitOptions(fs *flag.FlagSet){
	fs.StringVar(&o.Firstname,"firstname","oneslide","the firstname of the person")
	fs.StringVar(&o.Lastname,"lastname","icywater","lastname of the person")
	fmt.Println(os.Args)
	if os.Args[1] == "change"{
		fs.Parse(os.Args[2:])
	}

}

其中change为子命令

运行

$ go run main.go change -firstname zhang -lastname san
&{zhang san}
posted @ 2022-06-15 16:00  Oneslide  阅读(179)  评论(0编辑  收藏  举报