This is a creation in Article, where the information may have evolved or changed.
First, command-line Syntax
Command-line syntax is mainly in the following ways:
cmd -flag //只支持bool类型cmd -flag=xcmd -flag x //只支持非bool类型
The above syntax is the same for one or two '-' numbers
For plastic flag, the legal value can be 1234,0664,0x1234 or negative. For Boolean flag, it can be 1,0,t,f,t,f,true,false,true,false,true,false, etc.
Second, the command line parameter method
(1) defining the flag parameter
There are three parameters: the first is the parameter name, the second is the default value, and the third is a description
(1) through flag. A flag such as String (), Bool (), Int (). The Xxx () method, which returns a corresponding pointer
var ip = flag.Int("flagname", 1234, "help message for flagname")
(2) through flag. The Xxxvar () method binds the flag to a variable that returns a value type, such as
var flagvar intflag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
(3) through flag. Var () binds a custom type, the custom type needs to implement the value interface (receives must be a pointer), as
flag.Var(&flagVal, "name", "help message for flagname")
(2) call flag. Parse () parses the command-line argument to the defined flag
flag.Parse()
The parsing function will stop when it encounters the first non-flag command-line argument, which is a parameter that does not satisfy the command-line syntax, such as a command-line argument of CMD--flag=true ABC, and the first non-flag command-line argument is "ABC"
(3) after invoking parse parsing, you can directly use the flag itself (pointer type) or the bound variable (value type)
fmt.Println("flagvar has value ", flagvar)
Also available through flag. Args (), flag. ARG (i) to get non-flag command-line arguments
Third, examples
package mainimport ( "flag" "fmt") func main() { username := flag.String("name", "", "Input your username") flag.Parse() fmt.Println("Hello, ", *username)}
Compile:
go build flag.go
Run:
./flag -name=world
Output:
Hello, world