延迟执行和打印引用问题?

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

Defer and println reference issues?

问题

我想知道为什么是0而不是1?

那是一个指针而不是一个值。谢谢大家。

  1. package main
  2. import "fmt"
  3. func main() {
  4. var i = new(int)
  5. defer func(i *int) {
  6. fmt.Printf("3:%p,%v\n", i, *i)
  7. }(i)
  8. defer fmt.Printf("2:%p,%v\n", i, *i)
  9. *i++
  10. fmt.Printf("1:%p,%v\n", i, *i)
  11. }
  12. //1:0x1400001c0a0,1
  13. //2:0x1400001c0a0,0
  14. //3:0x1400001c0a0,1
英文:

I want to know why is there is 0 and not 1?

That is a pointer not a value.thanks guys.

  1. package main
  2. import "fmt"
  3. func main() {
  4. var i = new(int)
  5. defer func(i *int) {
  6. fmt.Printf("3:%p,%v\n", i, *i)
  7. }(i)
  8. defer fmt.Printf("2:%p,%v\n", i, *i)
  9. *i++
  10. fmt.Printf("1:%p,%v\n", i, *i)
  11. }
  12. //1:0x1400001c0a0,1
  13. //2:0x1400001c0a0,0
  14. //3:0x1400001c0a0,1

答案1

得分: 3

我希望这个简单明了的例子能帮助你理解文档中的内容。

  1. import "fmt"
  2. func params() int {
  3. fmt.Println("params")
  4. return 0
  5. }
  6. func f(int) {
  7. fmt.Println("deferred")
  8. }
  9. func main() {
  10. defer f(params())
  11. fmt.Println("exit")
  12. }

运行结果为:

  1. params
  2. exit
  3. deferred
英文:

I hope this simple and clear example will help to understand what is written in the documentation.

  1. import "fmt"
  2. func params() int {
  3. fmt.Println("params")
  4. return 0
  5. }
  6. func f(int) {
  7. fmt.Println("deferred")
  8. }
  9. func main() {
  10. defer f(params())
  11. fmt.Println("exit")
  12. }

and the result

  1. params
  2. exit
  3. deferred

答案2

得分: 0

延迟调用的参数会立即求值,但是函数调用直到周围的函数返回后才执行。

在第一个defer中,你使用了在调用func时接收到的参数i。
在第二个defer中,fmt.Printf("2:%p,%v\n", i, i),I的值已经在i++之前被求值。

英文:

The deferred call's arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.

In the first defer, you use the parameter i which is received when calling the func.
In the second defer fmt.Printf("2:%p,%v\n", i, *i), the value of I is already evaluated, before *i++

huangapple
  • 本文由 发表于 2022年2月27日 03:24:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/71279657.html
匿名

发表评论

匿名网友

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

确定