gpt4 book ai didi

go - 使用 defer 时在函数中返回值

转载 作者:IT王子 更新时间:2023-10-29 01:01:05 25 4
gpt4 key购买 nike

我在对返回值使用“延迟”时遇到了一些问题。我尝试以不同的方式运行一个测试函数(只是 i 的定义不同),但结果不同。所以,我对不同的返回值感到困惑。这是问题所在:

功能一:

package main
import "fmt"
func main() {
fmt.Println("a return:", a()) // return value: 0
}

func a() int {
var i int
defer func() {
i++
fmt.Println("a defer1:", i) // print " a defer1: 1"
}()
return i
}

返回值:

a defer1: 1
a return: 0

功能二:

package main
import "fmt"

func main() {
fmt.Println("a return:", a()) // return value: 1
}

func a() (i int) {
defer func() {
i++
fmt.Println("a defer1:", i) // print " a defer1: 1"
}()
return i
}

返回值:

a defer1: 1
a return: 1

返回值一个是0,另一个是1。所以,问题是这两个函数有什么区别。

最佳答案

what's the difference between the two functions?


The Go Programming Language Specification

Defer statements

A "defer" statement invokes a function whose execution is deferred to the moment the surrounding function returns.

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.

if the deferred function is a function literal and the surrounding function has named result parameters that are in scope within the literal, the deferred function may access and modify the result parameters before they are returned. If the deferred function has any return values, they are discarded when the function completes.


区别在于带有命名结果参数的外围函数

func a() (i int)

与具有未命名结果参数的周围函数相比

func a() int

关于go - 使用 defer 时在函数中返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53918738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com