英文:
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++
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论