无法通过指针获取函数的返回值。

huangapple go评论72阅读模式
英文:

cannot obain the function return values via pointers

问题

更新于2021年9月26日
我发现这是一个愚蠢的问题。

这是因为在调用flag.Parse()之后,标志将会被更新。

nReq := *flag_var
flag.Parse() // flag_var 更新
fmt.Println(nReq) // nReq 保持不变

因此,最佳实践是使用flag.IntVar(),这样我们可以输入更少的字符。


为什么我不能像这样使用返回值的指针类型?

// test.go
nReq := *flag.Int("n", 10000, "设置总请求数")
flag.Parse()
fmt.Println(nReq)

// test -n 200
10000
// 值仍然是10000。

它总是返回默认值(10000)。
我需要使用:

nReq := flag.Int("n", 10000, "设置总请求数")
flag.Parse()
fmt.Println(*nReq)

// test -n 200
200
// 值已更新为新的标志(200)
英文:

Update 2021-9-26
I found this is a stupid question.

This is because the flag will be updated after calling flag.Parse().

nReq := *flag_var
flag.Parse() // flag_var update
fmt.Println(nReq) // nReq is unchanged. 

Thus, the best practice is to use flag.IntVar() instead and we can type fewer chars.


Why can't I use the points types of return values like this?

// test.go
nReq := *flag.Int("n", 10000, "set total requests")
flag.Parse()
fmt.Println(nReq)

// test -n 200
10000
// the value is still 10000.

It always returns the default value(10000).
I need to use:

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)

答案1

得分: 4

flag.Int() 不会立即解析标志,它只会返回一个指向变量的指针,当解析时,标志值将存储在该变量中。

因此,如果你立即对其进行解引用,你将只得到你提供的默认值。你需要调用 flag.Parse()

如果你不想使用指针,可以在之前声明变量,并使用 flag.IntVar(),例如:

var nReq int
flag.IntVar(&nReq, "n", 10000, "设置总请求数")

flag.Parse()
fmt.Println(nReq)

现在 nReq 不是一个指针,你可以在不必一直解引用的情况下使用它。

另一种选择是继续使用 int.Var(),并在调用 flag.Parse() 之后 一次解引用返回的指针:

nReqPtr := flag.Int("n", 10000, "设置总请求数")
flag.Parse()

nReq := *nReqPtr
fmt.Println(nReq)
英文:

flag.Int() does not parse the flag "immediately", it just returns a pointer to a variable where the flag value will be stored when parsed.

So you if you dereference it right away, you'll just get the default value you provided. You have to call flag.Parse().

If you don't want to work with pointers, declare the variable prior, and use flag.IntVar(), for example:

var nReq int
flag.IntVar(&nReq, "n", 10000, "set total requests")

flag.Parse()
fmt.Println(nReq)

Now nReq is not a pointer, you may use it without having to dereference all the time.

Another option is to keep using int.Var(), and dereference the returned pointer once, after flag.Parse() has been called:

nReqPtr := flag.Int("n", 10000, "set total requests")
flag.Parse()

nReq := *nReqPtr
fmt.Println(nReq)

huangapple
  • 本文由 发表于 2021年9月24日 13:58:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/69310200.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定