hfSic

hfSic

flag包陷阱

背景#

flag.Bool以及flag.BoolVar會出現詭異的問題

當默認值設為 true

// flag.BoolVar
func main() {
	var getBool bool
	flag.BoolVar(&getBool, "get", true, "獲取布林值")
	flag.Parse()
	fmt.Println(getBool)
}
# 結果
go run main.go -get false
true
// flag.Bool
func main() {
	var getBool *bool
	getBool = flag.Bool("get", true, "獲取布林值")
	flag.Parse()
	fmt.Println(*getBool)
}
# 結果
go run main.go -get false
true

然而當默認值設為 false,將命令行參數設為true時,代碼結果又正常了(由於結果一致,只展示其中一種)

func main() {
	var getBool *bool
	getBool = flag.Bool("get", false, "獲取布林值")
	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
載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。