douxiong2999 2019-08-12 16:54
浏览 42
已采纳

去延迟函数返回值

func main() {

    println(DeferFunc1(1))
    println(DeferFunc2(1))
    println(DeferFunc3(1))
}

func DeferFunc1(i int) (t int) {
    t = i
    defer func() {
        t += 3
    }()
    return t
}

func DeferFunc2(i int) int {
    t := i
    defer func() {
        t += 3
    }()
    return t
}

func DeferFunc3(i int) (t int) {
    defer func() {
        t += i
    }()
    return 2
}

Above code will print: 4 1 3. Can anyone explain this? Of course, DeferFunc1 should return 4. But why will DeferFunc2 and DeferFunc3 will return 1 and 3 respectively? Is that about closure or variable scope in Go?

  • 写回答

1条回答 默认 最新

  • dongliang1893 2019-08-12 17:15
    关注

    If DeferFunc1 makes sense to you then DeferFunc3 should as well as they illustrate the same concept, namely that you can modify a named return value.

    In DeferFunc1 you are adding 3 to 1 in your defer yielding your expected 4.
    In DeferFunc3 you are adding 1 to 2 in your defer yielding 3. A naked return here, or a return of t would get you to 4. But in this case, t is assigned the value of 2 right before your defer runs, so you get 3.
    In DeferFunc2 you are not using a named return, so you cannot take advantage of this technique.

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

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序