Go Command Line Parsing: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 26: Line 26:
fmt.Println("flag i value: ", *iPtr)
fmt.Println("flag i value: ", *iPtr)
</pre>
</pre>
The rest of the command line arguments can be retrieved with <tt>flag.Args()</tt> that returns a <tt>string</tt> slice.


=Example=
=Example=

Revision as of 23:55, 1 April 2016

Internal

Overview

Go provides support for command line "flag" parsing in the flag package.

Flags (example: "-path=/something" or "-max=100") are declared with:

sPtr := flag.String("s", ".", "the path vale")
iPtr := flag.Int("i", 1, "the i value")

Note that the flag declaration methods return pointers that can be used to read the value of the flags after parsing:

flag.Parse()

Then their value is read from the previously obtained pointers:

fmt.Println("flag s value: ", *sPtr)
fmt.Println("flag i value: ", *iPtr)

The rest of the command line arguments can be retrieved with flag.Args() that returns a string slice.

Example

playground/go/command-line-args/command-line-arg-parser.go