基本函数说明
//生成命令行参数对应的变量,变量为指针类型
var name = flag.String("name", "Tom", "Input your name")
var age = flag.Int("age", 18, "Input your age")
var vip = flag.Bool("flag", true, "Is VIP")
其中"name","age","flag"对应在命令行中通过如下格式指定参数
-name=Jack
-name Jack
--name=Jack
--name Jack
//定义值类型的命令行参数变量,xxxVar对其进行初始化。可以为Int,String,Bool
var postCode int
flag.IntVar(&postCode, "Postcode", 1234, "Input your post code")
//接受命令行参数
flag.Parse()
//返回没有被解析的命令行参数的个数
flag.NArg()
//返回没有被解析的命令行参数
flag.Args()
//命令行设置的参数个数
flag.NFlag()
示例
package main
import (
"flag"
"fmt"
)
var name = flag.String("name", "Tom", "Input your name")
var age = flag.Int("age", 18, "Input your age")
var f = flag.Bool("isVIP", false, "Is VIP")
var postCode int
func init() {
flag.IntVar(&postCode, "postcode", 1234, "Input your post code")
}
func main() {
flag.Parse()
fmt.Println("name:", *name)
fmt.Println("age:", *age)
fmt.Println("VIP:", *f)
fmt.Println("postCode:", postCode)
fmt.Println("tail:", flag.Args())
fmt.Println(flag.NArg())
fmt.Println(flag.NFlag())
args := os.Args
fmt.Println("Args:", args)
paramCnt := flag.NArg()
for cnt := 0; cnt < paramCnt; cnt++ {
fmt.Println(flag.Arg(cnt))
}
}
执行测试
./flagtest -name=Bill -age=22 -isVIP=true --postcode=3235 otherParam1 otherParam2
name: Bill
age: 22
VIP: true
postCode: 3235
tail: [otherParam1 otherParam2]
2
4
Args: [./clitest -name=Bill -age=22 -isVIP=true --postcode=3235 otherParam1 otherParam2]
otherParam1
otherParam2
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。