flag包陷阱

背景

flag.Bool以及flag.BoolVar会出现诡异的问题

当默认值设为 true，

Copy
// flag.BoolVar
func main() {
var getBool bool
flag.BoolVar(&getBool, "get", true, "get a boolean")
flag.Parse()
fmt.Println(getBool)
}

Copy
# 结果
go run main.go -get false
true

Copy
// flag.Bool
func main() {
var getBool *bool
getBool = flag.Bool("get", true, "get a boolean")
flag.Parse()
fmt.Println(*getBool)
}

Copy
# 结果
go run main.go -get false
true

然而当默认值设为 false，将命令行参数设为true时，代码结果又正常了（由于结果一致，只展示其中一种）

Copy
func main() {
var getBool *bool
getBool = flag.Bool("get", false, "get a boolean")
flag.Parse()
fmt.Println(*getBool)
}

Copy
# 结果
go run main.go -get true
true

为什么

那么来看看代码注释

Copy
// src/flag/flag.go
// A Flag represents the state of a flag.
type Flag struct {
Name string // name as it appears on command line
Usage string // help message
Value Value // value as set
DefValue string // default value (as text); for usage message
}

// Value is the interface to the dynamic value stored in a flag.
// (The default value is represented as a string.)
//
// If a Value has an IsBoolFlag() bool method returning true,
// the command-line parser makes -name equivalent to -name=true
// rather than using the next command-line argument.
//
// Set is called once, in command line order, for each flag present.
// The flag package may call the [String] method with a zero-valued receiver,
// such as a nil pointer.
type Value interface {
String() string
Set(string) error
}

bool flag -name 会被 parser 解析为 - name= true 而不会解析下一个参数

Copy
# 如下 -b 后的 false 不会被解析
# 以下命令等同于 go run main.go -b=true
go run main.go -b false

如何解决

以-name=false来替代-name false

Copy
# 结果
go run main.go -get=true -come=false -num 1
true
false
1