2 回答

TA貢獻1818條經驗 獲得超3個贊
因為它們創建后需要賦值。動作順序是:
創建變量
var n = flag.Bool("n", false, "omit trailing newline")
現在值為 false。用 賦值
flag.Parse()
?,F在為變量分配了作為命令行參數傳遞的值。

TA貢獻1942條經驗 獲得超3個贊
如果您檢查此處的代碼,您將看到有一個名為 的導出變量CommandLine
,它是一個指向FlagSet
. 這就是奇跡發生的地方。當您導入該庫時,它就會被實例化。例如,當您調用導出函數時flag.Bool()
,該函數會依次調用方法 Bool()
,該方法有一個指向...的指針接收器FlagSet
。它將創建一個新的bool
來存儲標志的值,調用以存儲指向數據結構中BoolVar()
新創建的變量的指針(您需要跟蹤以了解這是如何完成的),然后將完全相同的指針返回給您,以便您稍后可以獲取當前的bool
FlagSet
BoolVar
值(可以是默認值,也可以是調用的結果的全新值Parse()
)
// CommandLine is the default set of command-line flags, parsed from os.Args.
// The top-level functions such as BoolVar, Arg, and so on are wrappers for the
// methods of CommandLine.
var CommandLine = NewFlagSet(os.Args[0], ExitOnError)
// NewFlagSet returns a new, empty flag set with the specified name and
// error handling property. If the name is not empty, it will be printed
// in the default usage message and in error messages.
func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {
f := &FlagSet{
name: name,
errorHandling: errorHandling,
}
f.Usage = f.defaultUsage
return f
}
// A FlagSet represents a set of defined flags. The zero value of a FlagSet
// has no name and has ContinueOnError error handling.
//
// Flag names must be unique within a FlagSet. An attempt to define a flag whose
// name is already in use will cause a panic.
type FlagSet struct {
// Usage is the function called when an error occurs while parsing flags.
// The field is a function (not a method) that may be changed to point to
// a custom error handler. What happens after Usage is called depends
// on the ErrorHandling setting; for the command line, this defaults
// to ExitOnError, which exits the program after calling Usage.
Usage func()
name string
parsed bool
actual map[string]*Flag
formal map[string]*Flag
args []string // arguments after flags
errorHandling ErrorHandling
output io.Writer // nil means stderr; use Output() accessor
}
// Bool defines a bool flag with specified name, default value, and usage string.
// The return value is the address of a bool variable that stores the value of the flag.
func (f *FlagSet) Bool(name string, value bool, usage string) *bool {
p := new(bool)
f.BoolVar(p, name, value, usage)
return p
}
// Bool defines a bool flag with specified name, default value, and usage string.
// The return value is the address of a bool variable that stores the value of the flag.
func Bool(name string, value bool, usage string) *bool {
return CommandLine.Bool(name, value, usage)
}
回到你的問題:
為什么變量 n 和 sep 是指向標志變量的指針,而不是普通變量類型。
這是因為Parse()
可以操縱原始變量和新變量n
,并且sep
只會捕獲原始值的副本。通過使用指針,您和其他人FlagSet
正在查看完全相同的變量。
- 2 回答
- 0 關注
- 168 瀏覽
添加回答
舉報