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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决