在Golang中使用defer
,i是命名的结果参数,其中返回值在返回值中已明确分配给IT,然后将其明确分配给IT,然后才能在递延之前明确分配。 Thus, the deferred increment affects the returned value, giving an output of 1.However, in c2(), even though i is returned explicitly as 2, the deferred increment modifies the result parameter, resulting in a return value of 3.
The specification clarifies this behavior:
Return statements:
A "return" statement that指定结果设置结果参数在执行任何延迟函数之前。func c(i int) int { defer func() { i }() return i } func c1() (i int) { defer func() { i }() return i } func c2() (i int) { defer func() { i }() return 2 }此原理都适用于函数和方法,在函数和方法中,延迟函数可以在返回之前访问和修改命名的结果参数。因此,考虑可变声明和延期函数修改如何影响最终返回值。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3