Go flag 使用

Go About 1,101 words

用途

使用命令行时指定字段赋值,类似Spring Bootjar包方式启动时根据不同环境设置不同值。

示例

var s string

var show bool

func main() {
    flag.StringVar(&s, "test_filed", "this is default value", "this is description")
    flag.BoolVar(&show, "show", false, "no description")
    flag.Parse()
}

针对字符串类型字段,-filed="value"-filed "value"两种赋值方式都可被flag.Parse()解析识别。

go run api_flag.go -test_filed="hello world"
go run api_flag.go -test_filed "hello world"

针对字符串类型字段,以下赋值方式都可赋值布尔类型。

go run api_flag.go -show
go run api_flag.go -show=true
go run api_flag.go -show=t
go run api_flag.go -show=T
go run api_flag.go -show=false
go run api_flag.go -show=f
go run api_flag.go -show=F
go run api_flag.go -show=0
go run api_flag.go -show=1

注意布尔类型的几种赋值方式。

-flag // 只支持bool类型
-flag=x
-flag x // 只支持非bool类型

非预设的参数赋值方式。

go run api_flag.go hello world test1 test2

非预设的参数接收方式。

func main() {
    fmt.Println("预设的flag的参数个数:", flag.NFlag())

    // go run api_flag.go hello world test1 test2
    fmt.Println("非预设的flag的参数:", flag.Args()) // [hello world test1 test2]
    fmt.Println(flag.Arg(0)) // hello
    fmt.Println("非预设的flag的参数个数:", flag.NArg())
}
Views: 2,472 · Posted: 2021-01-14

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh