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

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

Defer and println reference issues?

问题

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

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

package main

import "fmt"

func main() {
	var i = new(int)
	defer func(i *int) {
		fmt.Printf("3:%p,%v\n", i, *i)
	}(i)
	defer fmt.Printf("2:%p,%v\n", i, *i)
	*i++
	fmt.Printf("1:%p,%v\n", i, *i)
}

//1:0x1400001c0a0,1
//2:0x1400001c0a0,0
//3:0x1400001c0a0,1
英文:

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

That is a pointer not a value.thanks guys.

package main

import "fmt"

func main() {
	var i = new(int)
	defer func(i *int) {
		fmt.Printf("3:%p,%v\n", i, *i)
	}(i)
	defer fmt.Printf("2:%p,%v\n", i, *i)
	*i++
	fmt.Printf("1:%p,%v\n", i, *i)
}

//1:0x1400001c0a0,1
//2:0x1400001c0a0,0
//3:0x1400001c0a0,1

答案1

得分: 3

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

import "fmt"

func params() int {
    fmt.Println("params")
    return 0
}

func f(int) {
    fmt.Println("deferred")
}

func main() {
    defer f(params())
    fmt.Println("exit")
}

运行结果为:

params
exit
deferred
英文:

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

import "fmt"

func params() int {
	fmt.Println("params")
	return 0
}

func f(int) {
	fmt.Println("deferred")
}

func main() {
	defer f(params())
	fmt.Println("exit")
}

and the result

params
exit
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:

确定