版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32855219/article/details/82193066


  从第一次接触go就对flag包非常懵,因为只看到直接通过包名去调用flag.String(name,value,usage) 装入数据和flag.Parse() 之后取出数据,想不到居然有这样的内置包, 到底把数据存到了哪里呢?

Package flag implements command-line flag parsing.


Define flags using flag.String(), Bool(), Int(), etc.

This declares an integer flag, -flagname, stored in the pointer ip, with type *int.
    import "flag"
    var ip = flag.Int("flagname", 1234, "help message for flagname")
If you like, you can bind the flag to a variable using the Var() functions.
    var flagvar int
    func init() {
        flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
Or you can create custom flags that satisfy the Value interface (with
pointer receivers) and couple them to flag parsing by
    flag.Var(&flagVal, "name", "help message for flagname")
For such flags, the default value is just the initial value of the variable.

After all flags are defined, call
to parse the command line into the defined flags.

Flags may then be used directly. If you're using the flags themselves,
they are all pointers; if you bind to variables, they're values.
    fmt.Println("ip has value ", *ip)
    fmt.Println("flagvar has value ", flagvar)

After parsing, the arguments following the flags are available as the
slice flag.Args() or individually as flag.Arg(i).
The arguments are indexed from 0 through flag.NArg()-1.

Command line flag syntax:
    -flag x  // non-boolean flags only
One or two minus signs may be used; they are equivalent.
The last form is not permitted for boolean flags because the
meaning of the command
    cmd -x *
where * is a Unix shell wildcard, will change if there is a file
called 0, false, etc. You must use the -flag=false form to turn
off a boolean flag.

Flag parsing stops just before the first non-flag argument
("-" is a non-flag argument) or after the terminator "--".

Integer flags accept 1234, 0664, 0x1234 and may be negative.
Boolean flags may be:
    1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False
Duration flags accept any input valid for time.ParseDuration.

The default set of command-line flags is controlled by
top-level functions.  The FlagSet type allows one to define
independent sets of flags, such as to implement subcommands
in a command-line interface. The methods of FlagSet are
analogous to the top-level functions for the command-line
flag set.



func StringVar(p *string, name string, value string, usage string) {
    CommandLine.Var(newStringValue(value, p), name, usage)


// 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.
func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {
    f := &FlagSet{
        name:          name,
        errorHandling: errorHandling,
    f.Usage = f.defaultUsage
    return f


// defaultUsage is the default function to print a usage message.
func (f *FlagSet) defaultUsage() {
    if f.name == "" {
        fmt.Fprintf(f.Output(), "Usage:\n")
    } else {
        fmt.Fprintf(f.Output(), "Usage of %s:\n", f.name)


// PrintDefaults prints, to standard error unless configured otherwise, the
// default values of all defined command-line flags in the set. See the
// documentation for the global function PrintDefaults for more information.
func (f *FlagSet) PrintDefaults() {
    f.VisitAll(func(flag *Flag) {
        s := fmt.Sprintf("  -%s", flag.Name) // Two spaces before -; see next two comments.
        name, usage := UnquoteUsage(flag)
        if len(name) > 0 {
            s += " " + name
        // Boolean flags of one ASCII letter are so common we
        // treat them specially, putting their usage on the same line.
        if len(s) <= 4 { // space, space, '-', 'x'.
            s += "\t"
        } else {
            // Four spaces before the tab triggers good alignment
            // for both 4- and 8-space tab stops.
            s += "\n    \t"
        s += strings.Replace(usage, "\n", "\n    \t", -1)

        if !isZeroValue(flag, flag.DefValue) {
            if _, ok := flag.Value.(*stringValue); ok {
                // put quotes on the value
                s += fmt.Sprintf(" (default %q)", flag.DefValue)
            } else {
                s += fmt.Sprintf(" (default %v)", flag.DefValue)
        fmt.Fprint(f.Output(), s, "\n")


// Var defines a flag with the specified name and usage string. The type and
// value of the flag are represented by the first argument, of type Value, which
// typically holds a user-defined implementation of Value. For instance, the
// caller could create a flag that turns a comma-separated string into a slice
// of strings by giving the slice the methods of Value; in particular, Set would
// decompose the comma-separated string into the slice.
func (f *FlagSet) Var(value Value, name string, usage string) {
    // Remember the default value as a string; it won't change.
    flag := &Flag{name, usage, value, value.String()}
    _, alreadythere := f.formal[name]
    if alreadythere {
        var msg string
        if f.name == "" {
            msg = fmt.Sprintf("flag redefined: %s", name)
        } else {
            msg = fmt.Sprintf("%s flag redefined: %s", f.name, name)
        fmt.Fprintln(f.Output(), msg)
        panic(msg) // Happens only if flags are declared with identical names
    if f.formal == nil {
        f.formal = make(map[string]*Flag)
    f.formal[name] = flag

这样我们就明白了Flag包核心方法StringVar的实现,剩下的还有IntVar(), BoolVar()...这些方法都与此类似,各位可以自己去看。而另一个核心方法flag.Parse()的实现就不写了,留给大家自己去解读吧,应该是非常简单的


  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他