2 回答

TA貢獻(xiàn)1818條經(jīng)驗 獲得超3個贊
因為它們創(chuà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)驗 獲得超3個贊
如果您檢查此處的代碼,您將看到有一個名為 的導(dǎo)出變量CommandLine
,它是一個指向FlagSet
. 這就是奇跡發(fā)生的地方。當(dāng)您導(dǎo)入該庫時,它就會被實例化。例如,當(dāng)您調(diào)用導(dǎo)出函數(shù)時flag.Bool()
,該函數(shù)會依次調(diào)用方法 Bool()
,該方法有一個指向...的指針接收器FlagSet
。它將創(chuàng)建一個新的bool
來存儲標(biāo)志的值,調(diào)用以存儲指向數(shù)據(jù)結(jié)構(gòu)中BoolVar()
新創(chuàng)建的變量的指針(您需要跟蹤以了解這是如何完成的),然后將完全相同的指針返回給您,以便您稍后可以獲取當(dāng)前的bool
FlagSet
BoolVar
值(可以是默認(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)
}
回到你的問題:
為什么變量 n 和 sep 是指向標(biāo)志變量的指針,而不是普通變量類型。
這是因為Parse()
可以操縱原始變量和新變量n
,并且sep
只會捕獲原始值的副本。通過使用指針,您和其他人FlagSet
正在查看完全相同的變量。
- 2 回答
- 0 關(guān)注
- 166 瀏覽
添加回答
舉報