【发布时间】:2021-11-17 10:53:48
【问题描述】:
2021 年 9 月 26 日更新
我发现这是一个愚蠢的问题。
这是因为flag会在调用flag.Parse()后更新。
nReq := *flag_var
flag.Parse() // flag_var update
fmt.Println(nReq) // nReq is unchanged.
因此,最佳做法是改用 flag.IntVar(),我们可以输入更少的字符。
为什么我不能像这样使用积分类型的返回值?
// test.go
nReq := *flag.Int("n", 10000, "set total requests")
flag.Parse()
fmt.Println(nReq)
// test -n 200
10000
// the value is still 10000.
它总是返回默认值(10000)。
我需要使用:
nReq := flag.Int("n", 10000, "set total requests")
flag.Parse()
fmt.Println(*nReq)
// test -n 200
200
// the value is updated to the new flag(200)
【问题讨论】:
-
val1 := * function() 和 val2 := *val1 有什么区别
-
这样写是愚蠢的:val1 := func() *ptr, val2 := *val1。当我不想每次都写 *val1 时。
-
nReq = *func() 实际上无法获取标志的新值。它始终是默认值 (10000)。这可能是由于编译优化。
-
代码sn-p来自一个大程序,在这个例子中我省略了flag.Parse。
标签: go pointers command-line-arguments