Go flag 使用
Go 大约 1101 字用途
使用命令行时指定字段赋值,类似Spring Boot
以jar
包方式启动时根据不同环境设置不同值。
示例
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())
}
阅读 2366 · 发布于 2021-01-14
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
Spring Boot 中的 ApplicationRunner 和 CommandLineRunner阅读 3259
-
Java 并发编程之 CountDownLatch阅读 2243
-
Linux 使用 dd 查看日志增长速度、方法每秒执行次数阅读 1083
-
JMeter 更改报告中的时间戳格式阅读 2294
-
SQL 优化阅读 881
-
npm Hostname/IP does not match certificate's altnames阅读 3165
-
Spring 使用 filter 过滤器、ContentCachingWrapper 包装类获取请求参数和返回值阅读 1603
-
Windows 使用 PowerShell 保存 SSH 信息实现快捷登录阅读 3300
-
Go flag 使用阅读 2366
-
Linux CentOS 安装 MySQL5.7阅读 4498