Golang:如何禁用自动标志排序?

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

Golang: How to disable automatically flag sorting?

问题

使用flag包,我们可以像这样指定一些命令行参数:

  1. import "flag"
  2. func main() {
  3. from := flag.String("from", "", "要复制的路径")
  4. to := flag.String("to", "", "数据复制到的位置")
  5. ldb := flag.String("db", "./ldb", "复制过程中使用的数据库路径")
  6. pwd := flag.String("pwd", "", "加密数据的密码,默认情况下不对数据进行加密")
  7. flag.Parse()
  8. ...
  9. }

当使用-h参数获取帮助时,打印的消息似乎不是我提供的顺序:

  1. -db string
  2. 复制过程中使用的数据库路径 (默认为"./ldb")
  3. -from string
  4. 要复制的路径
  5. -pwd string
  6. 加密数据的密码,默认情况下不对数据进行加密
  7. -to string
  8. 数据复制到的位置

顺序不直观,是否有其他选项告诉Golang:“不要自动排序我的参数!”?

英文:

With flag package, we can specify some command line parameters like this:

  1. import "flag"
  2. fun main() {
  3. from := flag.String("from", "", "the path to be copied")
  4. to := flag.String("to", "", "where the data copied to")
  5. ldb := flag.String("db", "./ldb", "the database path used during copy")
  6. pwd := flag.String("pwd", "", "password to encrypt your data, default no encryption on your data"
  7. flag.Parse()
  8. ...
  9. }

When use -h for help, the printed message seems not the order I provided:

  1. -db string
  2. the database path used during copy (default "./ldb")
  3. -from string
  4. the path to be copied
  5. -pwd string
  6. password to encrypt your data, default no encryption on your data
  7. -to string
  8. where the data copy to

the order not intuitive, is there other options to tell Golang: Don't sort my parameter's automatically! ?

答案1

得分: 6

输出按字典顺序排序(https://golang.org/pkg/flag/#VisitAll):

> VisitAll按字典顺序访问命令行标志,对每个标志调用fn。它访问所有标志,即使那些未设置的标志也会被访问。

参见:https://golang.org/src/flag/flag.go#L435

您可以使用flag.FlagSet并使用自定义的Usage func()

英文:

The output is lexically sorted (https://golang.org/pkg/flag/#VisitAll):

> VisitAll visits the command-line flags in lexicographical order, calling fn for each. It visits all flags, even those not set.

See: https://golang.org/src/flag/flag.go#L435

You could use a flag.FlagSet and use a custom Usage func().

huangapple
  • 本文由 发表于 2016年3月31日 14:46:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/36326038.html
匿名

发表评论

匿名网友

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

确定