Go标志用法说明包含单词”value”。

huangapple go评论79阅读模式
英文:

Go Flag Usage Description Contains the Word value

问题

我已经定义了一个自定义标志,用于接受字符串切片,代码如下:

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
}

然后我使用以下代码进行解析:

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

当我构建这个程序并使用帮助标志运行它时:main -h,它会打印出:

Usage of main:
  -t value
        Test explanation

我的问题是,value这个词是从哪里来的?我找不到如何删除它的方法。我认为这可能与标志的默认值有关。

英文:

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.

答案1

得分: 1

valueflag.UnquoteUsage为自定义类型选择的默认参数名称(通过flag.(*FlagSet).PrintDefaults呈现)。

您可以使用反引号覆盖默认值在您的用法文本中。反引号将从用法文本中删除。例如:

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()
}

使用-h运行将显示参数名称的更改:

Usage of ./flagusage:
  -foo value
    	append a foo to the list
  -foo2 foo
    	append a foo to the list
英文:

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

huangapple
  • 本文由 发表于 2022年4月9日 19:05:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/71807493.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定