This is a creation in Article, where the information may have evolved or changed.
Recently want to do Apache thrift related projects. I probably looked at it and felt it was not difficult. Thrift is now and go language. Follow an official example of learning. Friday had a morning, and finally the compilation passed. In the afternoon to read the example source, found a never seen package--flag.
Both c development and Java have been exposed to command-line development. public static void main(String []args)
a command-line startup parameter can be read in the main function parameters of the big java. and the main function of the go language is decisive and nothing func main()
, need to use this package.
Although go is not like big Java, it is possible to get command line arguments directly inside the main function, but the type of argument that go takes with the flag packet, unlike Java, can only be a string type.
Before getting it, you need to customize the parameter name, parameter defaults, parameter usage, and parameter types you want to get. The pointer type is returned. You can also use a function StringVar
, just like the change in the parameter table and the return value.
func String(name string, value string, usage string) *stringfunc StringVar(p *string, name string, value string, usage string)
Once defined, it is automatically parsed by invoking the function of the flag packet Parse
. The complete example is as follows Testflag.go:
package mainimport ( "flag")var strFlag = flag.String("s", "", "Description")var boolFlag = flag.Bool("bool", false, "Description of flag")func main() { flag.Parse() println(*strFlag, *boolFlag)}
It is also important to note that the command-line arguments of go and the large Java counterparts are different, by default it is not possible to write only values, but also to pass in the name of the value, that is, the first argument of the function mentioned earlier String
. If you define it name
, you need to add it when you pass it -name {NAME}
.
Run commands and results:
$ go run testflag.go -s 123123 false
Now on GitHub, a new library of Go language-related use cases is created, with the usual test code in it. Add it starting today.
Https://github.com/mnhkahn/go_code
###### References + "1" package flag-http://golang.org/