Golang command source code
极客时间《Go 语言核心 36 讲》学习笔记 03,图片来自网络
02 | 命令源码文件
从隔壁的《Go 语言从入门到实战》的课程里面,学到实用 test 程序来进行语言的学习,似乎比用命令源码文件要方便一些,不需要每个程序都建立一个目录。
不过这篇专栏的内容还是最好写命令源码文件的,因为要传入参数。
flag.StringVar 类似于注册参数flag.String 返回的是存储命令参数值的地址flag.Parse 才是真正解析命令参数并且赋值的方法
手敲了一遍官网上 flag 的三个示例代码,学习专栏中不明白的地方也就都理解了。

对于思考题:
我从官网的说明中看到的是 string, bool 和 int,细分的类型可能需要看源码或者是方法的定义。
bool, float64, int, int64, string, uint64, uint, time.Duration
这个在专栏文中和官方示例中都有,只要有类型定义,并且传入符合要求的值即可。
type URLValue struct {
URL *url.URL
}
...
var u = &url.URL{}
...
fs := flag.NewFlagSet("ExmapleValue", flag.ExitOnError)
fs.Var(&URLValue{u}, "url", "URL to parse")
这一篇的留言比上一篇少了一半,是因为大家都觉的简单么?
Package flag implements command-line flag parsing.
Define flags using flag.String(), Bool(), Int(), etc.
This declares an integer flag, -n, stored in the pointer nFlag, with type *int:
import "flag"
var nFlag = flag.Int("n", 1234, "help message for flag n")
If you like, you can bind the flag to a variable using the Var() functions.
var flagvar int
func init() {
flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
}
Or you can create custom flags that satisfy the Value interface (with pointer receivers) and couple them to flag parsing by
flag.Var(&flagVal, "name", "help message for flagname")
After all flags are defined, call
flag.Parse()
to parse the command line into the defined flags.
Flags may then be used directly. If you're using the flags themselves, they are all pointers; if you bind to variables, they're values.
After parsing, the arguments following the flags are available as the slice flag.Args() or individually as flag.Arg(i). The arguments are indexed from 0 through flag.NArg()-1.