背景#
flag.Bool
以及flag.BoolVar
会出现诡异的问题
当默认值设为 true
,
// flag.BoolVar
func main() {
var getBool bool
flag.BoolVar(&getBool, "get", true, "get a boolean")
flag.Parse()
fmt.Println(getBool)
}
# 结果
go run main.go -get false
true
// flag.Bool
func main() {
var getBool *bool
getBool = flag.Bool("get", true, "get a boolean")
flag.Parse()
fmt.Println(*getBool)
}
# 结果
go run main.go -get false
true
然而当默认值设为 false
,将命令行参数设为true
时,代码结果又正常了(由于结果一致,只展示其中一种)
func main() {
var getBool *bool
getBool = flag.Bool("get", false, "get a boolean")
flag.Parse()
fmt.Println(*getBool)
}
# 结果
go run main.go -get true
true
为什么#
那么来看看代码注释
// 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 而不会解析下一个参数
# 如下 -b 后的 false 不会被解析
# 以下命令等同于 go run main.go -b=true
go run main.go -b false
如何解决#
以-name=false
来替代-name false
# 结果
go run main.go -get=true -come=false -num 1
true
false
1