我正在尝试Go,并且看到了一些延迟功能的意外行为。考虑下面的程序,该程序将全局变量增加给定的数量。
package main
import "fmt"
var z = 1
func main() {
defer increaseZ(10)
defer fmt.Println("z =", increaseZ(20), "Deferred Value 1")
defer fmt.Println("z =", increaseZ(30), "Deferred Value 2")
fmt.Println("z =", z, "Main Value")
}
func increaseZ(y int) int {
z += y
println("z =", z, "Inside Increase Function")
return z
}
z = 21 Inside Increase Function
z = 51 Inside Increase Function
z = 61 Inside Increase Function
z = 51 Main Value
z = 51 Deferred Value 2
z = 21 Deferred Value 1
defer fmt.Println("z =", increaseZ(20), "Deferred Value 1")
defer fmt.Println("z =", increaseZ(30), "Deferred Value 2")
defer increaseZ(10)
z = 21 Inside Increase Function
z = 51 Inside Increase Function
z = 51 Main Value
z = 61 Inside Increase Function
z = 51 Deferred Value 2
z = 21 Deferred Value 1
The deferred call's arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.
increaseZ
作为参数,但是直到主函数返回后才调用defer increaseZ(10)
。increaseZ(10)
。您的打印目的地不一致。
stdout: fmt.Println
stderr: println
package main
import "fmt"
var z = 1
func main() {
defer increaseZ(10)
defer fmt.Println("z =", increaseZ(20), "Deferred Value 1")
defer fmt.Println("z =", increaseZ(30), "Deferred Value 2")
fmt.Println("z =", z, "Main Value")
}
func increaseZ(y int) int {
z += y
fmt.Println("z =", z, "Inside Increase Function")
return z
}
z = 21 Inside Increase Function
z = 51 Inside Increase Function
z = 51 Main Value
z = 51 Deferred Value 2
z = 21 Deferred Value 1
z = 61 Inside Increase Function
package main
import (
"fmt"
"os"
)
var z = 1
func main() {
defer increaseZ(10)
defer fmt.Fprintln(os.Stderr, "z =", increaseZ(20), "Deferred Value 1")
defer fmt.Fprintln(os.Stderr, "z =", increaseZ(30), "Deferred Value 2")
fmt.Fprintln(os.Stderr, "z =", z, "Main Value")
}
func increaseZ(y int) int {
z += y
println("z =", z, "Inside Increase Function")
return z
}
z = 21 Inside Increase Function
z = 51 Inside Increase Function
z = 51 Main Value
z = 51 Deferred Value 2
z = 21 Deferred Value 1
z = 61 Inside Increase Function
关于go - Go-延迟函数的不一致评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29316958/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |