💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[TOC] ## 实例 ### 默认带 --help 查询 ``` var ( s string ) func main() { flag.StringVar(&s,"name", "cc", "input you name") flag.Parse() fmt.Printf("%+v\n", s) } ``` 运行 ``` > go run main.go --help -name string input you name (default "cc") > go run main.go --name cpj //只能用 --name, -name无效 cpj ``` ### 主动打印 help 信息 ``` var ( help bool file string number int ) func init() { flag.BoolVar(&help, "h", false, "this is help") // `file` 写在最后的注释中,可使 -f string 改为 -f file flag.StringVar(&file, "f", "", "this is a `file`") flag.IntVar(&number, "n", 0, "tshi is a `number`") flag.Usage = usage } func main() { flag.Parse() if file != "" { log.Println("file is ", file) lookup := flag.Lookup("f") // 打印参数的数据 fmt.Printf("%+v\n", lookup) //&{Name:f Usage:this is a `file` Value:test.file DefValue:} } if number != 0 { log.Println("number is", number) } fmt.Println(flag.Args()) if help { //主动打印信息 flag.Usage() } } func usage() { fmt.Fprintf(os.Stdout, `test version: test/1.10.0 Usage: test [-hvVtTq] [-s signal] [-c filename] [-p prefix] [-g directives] Options: `) flag.PrintDefaults() } ``` output ``` Usage: test [-hvVtTq] [-s signal] [-c filename] [-p prefix] [-g directives] Options: -f file this is a file -h this is help -n number tshi is a number ```