Flag Pack
Implementation of command line flag parsing
Usage
Func string (name string, value string, usage String) *string
string defines a string that specifies the name of flag, the default value, and usage. The return value is a string-type address that holds the value of Flage
Func stringvar (P *string, name string, value string, usage string)
Stringvar defines a string of type flage that specifies the name, the default value, and usage. The parameter P pointer points to the space where the flag value exists.
Func Var (value value, name string, usage string)
Var defines the flag named name and usage. The first input parameter is the value of flag, type value, which can hold the value of the user-defined implementation. For example, the user can create a flag, and the incoming parameters are separated by commas into a slice.
- Func Args () []string
Args returns command-line arguments without flag.
Example 1
Package Mainimport ("Errors" "Flag" "FMT" "Strings" "Time") var species = flag. String ("Species", "gopher", "The species we are studying") var gophertype stringvar gopherType1 stringvar intervalflag inte Rvalfunc init () {const (Defaultgopher = "pocket" Usage = "the variety of gopher") Flag.s Tringvar (&gophertype, "Gopher_type", Defaultgopher, usage) flag. Stringvar (&gophertype1, "G", Defaultgopher, usage+ "(shorthand)") flag. Var (&intervalflag, "DeltaT", "comma-separated list of intervals to use between events")}type interval []time. Durationfunc (i *interval) string () string {return FMT. Sprint (*i)}func (i *interval) Set (value string) error {if Len (*i) > 0 {return errors. New ("Interval flag already set")} for _, dt: = Range strings. Split (Value, ",") {duration, err: = time. Parseduration (DT) If err! = Nil {return err} *i = Append (*i, duration)} return NI LFunc main () {flag. Parse () fmt. Println ("Species:", *species) fmt. Println ("Gophertype:", Gophertype) fmt. Println ("GopherType1:", GopherType1) fmt. Println ("Intervalflag:", Intervalflag)}
Compile run
go build flag.go ./flag -species dog -g chicken -gopher_type bird -deltaT 10s,15s,1m,1h
Run results
species: doggopherType: birdgopherType1: chickenintervalFlag: [10s 15s 1m0s 1h0m0s]
Example 2
package mainimport ( "fmt" "flag")func main() { flag.Parse() args := flag.Args() for index, val := range args { fmt.Printf("arg%v: %v \n", index, val) } return}
Run results
Example 3
package mainimport ( "fmt" "os")func main() { for index, val := range os.Args { fmt.Printf("arg%v: %v \n", index, val) } return}
Run results
Go Language-flag Use