dongqiu5184 2018-12-25 01:32
浏览 34
已采纳

使用延迟时函数中的返回值

I have some problem with using 'defer' about the return value. I tried to run one test function in different way (only the definition of i is different), but the result is different. So, I'm confused about the different return value. Here is the problem:

function 1:

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
}

return value:

a defer1: 1
a return: 0

function 2:

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
}

return value:

a defer1: 1
a return: 1

One of the return values is 0, the other is 1. So, the question is what's the difference between the two function.

  • 写回答

1条回答 默认 最新

  • dongxiandi8313 2018-12-25 01:59
    关注

    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.


    The difference is a surrounding function with a named result parameter

    func a() (i int)
    

    versus a surrounding function with an unnamed result parameter

    func a() int
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制