2 回答
TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超3個(gè)贊
因?yàn)樗鼈儎?chuàng)建后需要賦值。動(dòng)作順序是:
創(chuàng)建變量
var n = flag.Bool("n", false, "omit trailing newline")現(xiàn)在值為 false。用 賦值
flag.Parse()?,F(xiàn)在為變量分配了作為命令行參數(shù)傳遞的值。
TA貢獻(xiàn)1942條經(jīng)驗(yàn) 獲得超3個(gè)贊
如果您檢查此處的代碼,您將看到有一個(gè)名為 的導(dǎo)出變量CommandLine,它是一個(gè)指向FlagSet. 這就是奇跡發(fā)生的地方。當(dāng)您導(dǎo)入該庫(kù)時(shí),它就會(huì)被實(shí)例化。例如,當(dāng)您調(diào)用導(dǎo)出函數(shù)時(shí)flag.Bool(),該函數(shù)會(huì)依次調(diào)用方法 Bool(),該方法有一個(gè)指向...的指針接收器FlagSet。它將創(chuàng)建一個(gè)新的bool來(lái)存儲(chǔ)標(biāo)志的值,調(diào)用以存儲(chǔ)指向數(shù)據(jù)結(jié)構(gòu)中BoolVar()新創(chuàng)建的變量的指針(您需要跟蹤以了解這是如何完成的),然后將完全相同的指針?lè)祷亟o您,以便您稍后可以獲取當(dāng)前的boolFlagSetBoolVar值(可以是默認(rèn)值,也可以是調(diào)用的結(jié)果的全新值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)
}
回到你的問(wèn)題:
為什么變量 n 和 sep 是指向標(biāo)志變量的指針,而不是普通變量類型。
這是因?yàn)?code>Parse()可以操縱原始變量和新變量n,并且sep只會(huì)捕獲原始值的副本。通過(guò)使用指針,您和其他人FlagSet正在查看完全相同的變量。
- 2 回答
- 0 關(guān)注
- 195 瀏覽
添加回答
舉報(bào)
