3 回答
TA贡献1859条经验 获得超6个赞
您的打印目的地不一致。
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
- 3 回答
- 0 关注
- 237 浏览
添加回答
举报