douping7975 2017-03-09 19:18
浏览 49
已采纳

当defer func评估其参数时

I am learning how defer behaves in golang, and want to use it to handle error when the function returns.

Code is as below:

package main

import "fmt"
import "errors"

func main() {
    a()
}

func a() {
    var err error   
    defer func(){
        if err != nil {
            fmt.Printf("1st defer: %s
", err)
        } else {
            fmt.Println("1st defer: defer not error")
        }
    }()
    defer func(err error){
        if err != nil {
            fmt.Printf("2nd defer: %s
", err)
        } else {
            fmt.Println("2nd defer: defer not error")
        }
    }(err)

    err = errors.New("new error")
    if err != nil {
        return
    }
}

The output:

2nd defer: defer not error
1st defer: new error

Doc says parameters are evaluated when the defer call is evaluated, which seems it should be consistent. Why 2 defer has different value for variable err and thusly different output? I know it is related to 2nd function has err as input parameter, but don't know why.

  • 写回答

3条回答 默认 最新

  • dqroktbn005028 2017-03-09 19:28
    关注

    Ok I just figured out. If you pass any parameters to the defer func (like the 2nd defer function above), those parameters are evaluated when the defer function is deferred, not when they are executed. That means in my example err is still nil and has not been assigned to a new error yet.

    on the other hand, in 1st defer above, err is not a parameter, but a variable in function a, and when 1st defer is executed, it has already been assigned to a new error.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)