由函数编辑的常量 return 是否自动成为命名 return 变量的值
Does a constant returned by a function automatically become the value of the named return variable
这是 Golang 中的一个函数,它使用 defer 来更改函数 c() 的命名 return 值。
package main
import "fmt"
func c() (i int) {
defer func() { }()
defer fmt.Println("our i is", i)
return 45
}
func main() {
fmt.Println(c())
}
程序的输出是:
our i is 0
45
更改代码中的匿名 func()
func c() (i int) {
defer func() { i = 1 }()
defer fmt.Println("our i is", i)
return 45
}
func main() {
fmt.Println(c())
}
这导致输出:
our i is 0
1
如果 i 中没有其他值,似乎 return 值 45 会自动复制到 i。但我不是 100% 确定这是否是输出的确切原因
在延迟函数中,您有机会修改结果参数的值。
调用延迟函数时,已设置 return
语句中指定的值。
如果有多个延迟函数,它们将按 LIFO 顺序执行(后进先出)。
在您的第二个示例中,首先执行 fmt.Println()
,然后是另一个匿名函数。
但是你需要知道的是,当 defer
语句被执行时,延迟函数的参数会被立即评估,而不是当延迟函数将是 运行 时(稍后,在返回之前).
Each time a "defer" statement executes, the function value and parameters to the call are evaluated as usual and saved anew but the actual function is not invoked. Instead, deferred functions are invoked immediately before the surrounding function returns, in the reverse order they were deferred.
所以这一行:
defer fmt.Println("our i is", i)
总是意味着用 i = 0
参数调用 fmt.Println()
:
fmt.Println("our i is", 0)
因为当这一行运行s时,i
的值为0
.
所以在你的第二个例子中 fmt.Println()
打印 0
,然后 运行s 另一个延迟函数将 i
设置为 1
这就是返回。
你的第一个例子只是打印一些东西(i = 0
),但是第一个例子中的延迟函数不修改 i
的值所以 45
将被返回(并打印通过 main()
中的 fmt.Println()
函数。
有关该主题的更多信息,请参阅以下内容questions/answer:
这是 Golang 中的一个函数,它使用 defer 来更改函数 c() 的命名 return 值。
package main
import "fmt"
func c() (i int) {
defer func() { }()
defer fmt.Println("our i is", i)
return 45
}
func main() {
fmt.Println(c())
}
程序的输出是:
our i is 0
45
更改代码中的匿名 func()
func c() (i int) {
defer func() { i = 1 }()
defer fmt.Println("our i is", i)
return 45
}
func main() {
fmt.Println(c())
}
这导致输出:
our i is 0
1
如果 i 中没有其他值,似乎 return 值 45 会自动复制到 i。但我不是 100% 确定这是否是输出的确切原因
在延迟函数中,您有机会修改结果参数的值。
调用延迟函数时,已设置 return
语句中指定的值。
如果有多个延迟函数,它们将按 LIFO 顺序执行(后进先出)。
在您的第二个示例中,首先执行 fmt.Println()
,然后是另一个匿名函数。
但是你需要知道的是,当 defer
语句被执行时,延迟函数的参数会被立即评估,而不是当延迟函数将是 运行 时(稍后,在返回之前).
Each time a "defer" statement executes, the function value and parameters to the call are evaluated as usual and saved anew but the actual function is not invoked. Instead, deferred functions are invoked immediately before the surrounding function returns, in the reverse order they were deferred.
所以这一行:
defer fmt.Println("our i is", i)
总是意味着用 i = 0
参数调用 fmt.Println()
:
fmt.Println("our i is", 0)
因为当这一行运行s时,i
的值为0
.
所以在你的第二个例子中 fmt.Println()
打印 0
,然后 运行s 另一个延迟函数将 i
设置为 1
这就是返回。
你的第一个例子只是打印一些东西(i = 0
),但是第一个例子中的延迟函数不修改 i
的值所以 45
将被返回(并打印通过 main()
中的 fmt.Println()
函数。
有关该主题的更多信息,请参阅以下内容questions/answer: