Home > Blockchain >  Go Flag Usage Description Contains the Word value
Go Flag Usage Description Contains the Word value

Time:04-12

I've defined a custom flag for accepting a slice of strings as such:

type strSliceFlag []string

func (i *strSliceFlag) String() string {
    return fmt.Sprint(*i)
}

func (i *strSliceFlag) Set(value string) error {
    *i = append(*i, value)
    return nil
}

I then parse it with

    ...
    var tags strSliceFlag
    flag.Var(&tags, "t", tFlagExpl)
    flag.Parse()
    ...

When I build this program, and run it with the help flag: main -h, it prints out:

Usage of main:
  -t value
        Test explanation

My question is, where is the word value coming from? I can't find out how to remove it. I think it maybe has something to do with the default value for the flag.

CodePudding user response:

value is the default argument name chosen by flag.UnquoteUsage for custom types (rendered via flag.(*FlagSet).PrintDefaults).

You can override the default with backquotes in your usage text. The backquotes are stripped from usage text. Eg:

package main

import (
    "flag"
    "fmt"
)

type stringSlice []string

func (s *stringSlice) String() string {
    return fmt.Sprint(*s)
}

func (s *stringSlice) Set(v string) error {
    *s = append(*s, v)
    return nil
}

func main() {
    var s stringSlice
    flag.Var(&s, "foo", "append a foo to the list")
    flag.Var(&s, "foo2", "append a `foo` to the list")
    flag.Parse()
}

Running with -h shows how the argument name changes:

Usage of ./flagusage:
  -foo value
        append a foo to the list
  -foo2 foo
        append a foo to the list
  •  Tags:  
  • go
  • Related