flag.Value接口来帮助我们定义命令行标志
package flag
type Value interface {
String() string
Set(string) error //解析传入的字符串并更新标志值
}
flag.CommandLine全局变量处理标志值:
type OM struct {
n1 string
}
func (om *OM) String() string {
return om.n1
}
func (om *OM) Set(s string) error {
om.n1 = s
return nil
}
func OMFlag(name string, value string, usage string) *OM {
om := OM{value} //初始值
flag.CommandLine.Var(&om, name, usage) //传值
return &om
}
主函数:
om1 := OMFlag("om1", "hi1", "say something")
om2 := OMFlag("om2", "hi2", "say something")
flag.Parse()
fmt.Println(om1, om2) //默认值hi1 hi2