getopt-like behavior in Go

前端 未结 9 828
南笙
南笙 2021-02-07 11:33

How do I nicely parse a list of program parameters and automate handling \"--help\" and/or \"--version\" (such as \"program [-d value] [--abc] [FILE1]\") in Go?

9条回答
  •  面向向阳花
    2021-02-07 11:55

    As a simple library, you have since August 2017 github.com/rsc/getopt

    To use, define flags as usual with package flag. Then introduce any aliases by calling getopt.Alias:

    getopt.Alias("v", "verbose")
    

    Or call getopt.Aliases to define a list of aliases:

    getopt.Aliases(
        "v", "verbose",
        "x", "xylophone",
    )
    

    And:

    In general Go flag parsing is preferred for new programs, because it is not as pedantic about the number of dashes used to invoke a flag (you can write -verbose or --verbose, and the program does not care).

    This package is meant to be used in situations where, for legacy reasons, it is important to use exactly getopt(3) syntax, such as when rewriting in Go an existing tool that already uses getopt(3).

提交回复
热议问题