简介
在Go-goroutines中已经涉及到过命令行参数,参见该文的getParams()函数。
为了避免用户自己解析os.Args,Go提供了一个package flag,对命令行参数的处理方法做了封装。
示例
package main
import (
"fmt"
"flag"
)
/*
D:\examples>go run helloworld.go
Hello, Tom! 2 + 3 = 5
Args' length: 0
D:\examples>go run helloworld.go -first 20 -second 30
Hello, Tom! 20 + 30 = 50
Args' length: 0
D:\examples>go run helloworld.go -name Jerry -first 20
Hello, Jerry! 20 + 3 = 23
Args' length: 0
D:\examples>go run helloworld.go -name Jerry -first 20 -second 300
Hello, Jerry! 20 + 300 = 320
Args' length: 0
D:\examples>go run helloworld.go -name Jerry -first 20 -second 300 other_arguments
Hello, Jerry! 20 + 300 = 320
Args' length: 1
other_arguments
D:\examples>
*/
func main() {
first := flag.Int("first", 2, "first number")
second := flag.Int("second", 3, "second number")
name := flag.String("name", "Tom", "user name")
flag.Parse()
ret := *first + *second
fmt.Printf("Hello, %s! %d + %d = %d\n", *name, *first, *second, ret)
args := flag.Args()
argsLen := len(args)
fmt.Println("Args' length:", argsLen)
if args != nil { // or argsLen > 0
for _, arg := range args {
fmt.Println(arg)
}
}
}
可以看到,在传参方面,和Linux、Python的习惯用法是一样的。——差别在于Go没有short options和long options之分,也无-和–符合之差异。–会被看做-,或视作结束符。
调用方法
结合前面的例子,直接给出src/flag/flag.go最前面的使用说明:
Package flag implements command-line flag parsing.
Usage:
Define flags using flag.String(), Bool(), Int(), etc.
This declares an integer flag, -flagname, stored in the pointer ip, with type *int.
import "flag"
var ip = flag.Int("flagname", 1234, "help message for flagname")
If you like, you can bind the flag to a variable using the Var() functions.
var flagvar int
func init() {
flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
}
Or you can create custom flags that satisfy the Value interface (with
pointer receivers) and couple them to flag parsing by
flag.Var(&flagVal, "name", "help message for flagname")
For such flags, the default value is just the initial value of the variable.
After all flags are defined, call
flag.Parse()
to parse the command line into the defined flags.
Flags may then be used directly. If you're using the flags themselves,
they are all pointers; if you bind to variables, they're values.
fmt.Println("ip has value ", *ip)
fmt.Println("flagvar has value ", flagvar)
After parsing, the arguments following the flags are available as the
slice flag.Args() or individually as flag.Arg(i).
The arguments are indexed from 0 through flag.NArg()-1.
Command line flag syntax:
-flag
-flag=x
-flag x // non-boolean flags only
One or two minus signs may be used; they are equivalent.
The last form is not permitted for boolean flags because the
meaning of the command
cmd -x *
will change if there is a file called 0, false, etc. You must
use the -flag=false form to turn off a boolean flag.
Flag parsing stops just before the first non-flag argument
("-" is a non-flag argument) or after the terminator "--".
Integer flags accept 1234, 0664, 0x1234 and may be negative.
Boolean flags may be:
1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False
Duration flags accept any input valid for time.ParseDuration.
The default set of command-line flags is controlled by
top-level functions. The FlagSet type allows one to define
independent sets of flags, such as to implement subcommands
in a command-line interface. The methods of FlagSet are
analogous to the top-level functions for the command-line
flag set.
后记
至本文,算是对Introducing Go一书快速过了一遍,相关总结告一段落。