Parameter resolution for Go language (flag)

Source: Internet
Author: User

Flag parameter parsing, I thought it would, the results found today, the original is more powerful than I remember.
Just take a moment to remember.
The first example is a common usage:
Flag Example 1//author:xiong Chuan liang//date:2015-4-10package mainimport ("Flag" "FMT" "OS") var (levelflag = flag.) Int ("Level", 0, "levels")   Bnflag int  ) func init () {flag. Intvar (&bnflag, "bn", 3, "number of copies")  }func Main () {flag. Parse ()      count: = Len (OS. Args)    FMT. PRINTLN ("Total number of parameters:", count)    FMT. PRINTLN ("parameter details:") for    I: = 0; I < count; i++{        FMT. Println (i, ":", OS.) Args[i])    }       fmt. Println ("\ n parameter value:") fmt. Println ("Level:", *levelflag) fmt. Println ("Copies:", Bnflag)}/* run Result: C:\temp\testflag>go run tf2.go-level 3-bn=2 parameters total: 4 parameter details: 0:c:\docume~1\admini~1\ Locals~1\temp\go-build158983983\command-line-arguments\_obj\exe\tf2.exe1:-level2:33:-bn=2 parameter value: Level: 3 copies: 2*/

The second example, you can extend the functionality:
Flag Example 2//author:xiong Chuan liang//date:2015-4-10package mainimport ("Flag" "FMT" "OS" "Time") Var (/* Error handling when parameter parsing error switch f.errorhandling {case Continueonerror:return errcase ExitOnError:os.Exit (2) Paniconerror: Panic (err)} *///flagset = flag. Newflagset (OS. Args[0],flag. Paniconerror) Flagset = flag. Newflagset (OS. Args[0],flag. Exitonerror)//flagset = flag. Newflagset ("Xcl", flag. Exitonerror) Verflag = flagset.string ("ver", "" "," version ") Xtimeflag = Flagset.duration (" Time ", 10*time. Minute, "Time Duration") Addrflag = stringarray{}) Func init () {Flagset.var (&addrflag, "a", "B")}func main () {FMT. PRINTLN ("OS. Args[0]: ", OS. Args[0]) flagset.parse (OS. Args[1:])//flagset.parse (OS. Args[0:]) fmt. Println ("Number of current command line parameter types:", Flagset.nflag ()) for I: = 0; I! = Flagset.narg (); i++ {fmt. Printf ("arg[%d]=%s\n", I, flag. ARG (i))} FMT. Println ("\ n parameter value:") fmt. Println ("ver:", *verflag) fmt. Println ("Xtimeflag:", *xtimeflag) fmt. Println ("Addrflag:", addrflag.string ()) for I,param: = Range flag. Args () {        Fmt. PRINTF ("---#%d:%s\n", I,param)}}type Stringarray []stringfunc (S-*stringarray) string () string {return FMT. Sprint ([]string (*s))}func (S *stringarray) Set (value string) error {*s = append (*s, value) return nil}/* run Result: C:\TEMP\ Testflag>go run Tfs.go-ver 9.0-a ba-a ca-a d2-ver 10.0-time 2m0sos. Args[0]: c:\docume~1\admini~1\locals~1\temp\go-build341936307\command-line-arguments\_obj\exe\ Tfs.exe current command line parameter types: 3 parameter value: Ver:10.0xtimeflag:2m0saddrflag: [BA ca d2]c:\temp\testflag>go run tfs.go-ver 9.0-a ba-a C A-a d2-ver 10.0os. Args[0]: c:\docume~1\admini~1\locals~1\temp\go-build712958211\command-line-arguments\_obj\exe\ Tfs.exe current command line parameter types: 2 parameter value: Ver:10.0xtimeflag:10m0saddrflag: [ba ca d2]--flagset = flag. Newflagset (OS. Args[0],flag. Paniconerror) Results: C:\temp\testflag>go run tfs.go-ver 9.0-a ba-a ca-a d2-ver 10.0-time 2m0s33os. Args[0]: C:\docume~1\admini~1\locals~1\temp\go-build841833143\command-line-arguments\_obj\exe\tfs.exeinvalid Value "2m0s33" for Flag-timE:time:missing unit in duration 2m0s33usage of c:\docume~1\admini~1\locals~1\temp\go-build841833143\ Command-line-arguments\_obj\exe\tfs.exe:-a=[]: B-time=10m0s:time duration-ver= "": Versionpanic:invalid value "2m0s Flag-time:time:missing unit in Duration 2m0s33goroutine 1 [running]:flag. (*flagset). Parse (0x10b18180, 0x10b42008, 0xc, 0xc, 0x0, 0x0) c:/go/src/flag/flag.go:814 +0xeemain.main () C:/TEMP/TESTFL ag/tfs.go:41 +0x163exit status 2--flagset = flag. Newflagset (OS. Args[0],flag. Exitonerror) Results: C:\temp\testflag>go run tfs.go-ver 9.0-a ba-a ca-a d2-ver 10.0-time 2m0s33os. Args[0]: C:\docume~1\admini~1\locals~1\temp\go-build501686683\command-line-arguments\_obj\exe\tfs.exeinvalid Value "2m0s33" for flag-time:time:missing unit in duration 2m0s33usage of C:\DOCUME~1\ADMINI~1\LOCALS~1\TEMP\GO-BUILD50 1686683\command-line-arguments\_obj\exe\tfs.exe:-a=[]: B-time=10m0s:time duration-ver= "": Versionexit status 2*/
The Flagset class allows for more flexible parameter handling.
Among them Newflagset:
Flagset = flag. Newflagset ("Xcl", flag. Exitonerror)
The first parameter of the Newflagset can be arbitrarily fixed. But the second argument determines how the error is handled when a parameter parsing error occurs.

If you want to extend the parameter definition, simply implement the following interface:
Type Value Interface {string () Stringset (string) Error}
As Stringarray in the example. It can be implemented as:
-A ba-a ca-a D2
Addrflag: [BA ca D2]

This effect.
You know, the same:
-ver 9.0-ver 10.0
The final result is that the ver:10.0 is the parameter that only identifies the last time.

The getopt () series function compared to Linux. Flag Packet This approach is still clearer and more straight-minded.


blog:http://blog.csdn.net/xcl168


Parameter resolution for Go language (flag)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.