MDGSF Software Engineer

[GO] flag获取命令行参数

2017-09-28
GO

package main

import (
    "flag"
    "fmt"
)

var name = flag.String("name", "gerry", "input username")
var age = flag.Int("age", 27, "input user age")

var ip int

func init() {
    flag.IntVar(&ip, "flagname", 1234, "help message for flagname")
}

func main() {
    flag.Parse()

    fmt.Printf("args = %s, num = %d\n", flag.Args(), flag.NArg())
    for i := 0; i != flag.NArg(); i++ {
        fmt.Printf("arg[%d] = %s\n", i, flag.Arg(i))
    }

    fmt.Println(*name)
    fmt.Println(*age)
    fmt.Println(ip)
}
e:\Go\GOPATH\src\jian\flagDemo>go run flagDemo.go aaa
args = [aaa], num = 1
arg[0] = aaa
gerry
27
1234

e:\Go\GOPATH\src\jian\flagDemo>go run flagDemo.go --name "jian" -age=18 -flagname=33 aaa bbb ccc ddd
args = [aaa bbb ccc ddd], num = 4
arg[0] = aaa
arg[1] = bbb
arg[2] = ccc
arg[3] = ddd
jian
18
33

weixingongzhonghao

上一篇 [GO] struct 组合

Comments

Content