douzui0143 2017-12-02 12:36
浏览 104
已采纳

在Go中使用defer

What is the use of defer in Go? The language documentation says it is executed when the surrounding function returns. Why not just put the code at end of given function?

  • 写回答

6条回答 默认 最新

  • dongren5293 2017-12-02 12:44
    关注

    We usually use defer to close or deallocate resources.

    A surrounding function executes all deferred function calls before it returns, even if it panics. If you just place a function call at the end of a surrounding function, it is skipped when panic happens.

    Moreover a deferred function call can handle panic by calling the recover built-in function. This cannot be done by an ordinary function call at the end of a function.

    Each deferred call is put on stack, and executed in reverse order when the surrounding function ends. The reversed order helps deallocate resources correctly.

    The defer statement must be reached for a function to be called.

    You can think of it as another way to implement try-catch-finally blocks.

    Closing like try-finally:

    func main() {
        f, err := os.Create("file")
        if err != nil {
            panic("cannot create file")
        }
        defer f.Close()
        // no matter what happens here file will be closed
        // for sake of simplicity I skip checking close result
        fmt.Fprintf(f,"hello")
    }
    

    Closing and panic handling like try-catch-finally

    func main() {
        defer func() {
            msg := recover()
            fmt.Println(msg)
        }()
        f, err := os.Create(".") // . is a current directory
        if err != nil {
            panic("cannot create file")
        }
        defer f.Close()
        // no matter what happens here file will be closed
        // for sake of simplicity I skip checking close result
        fmt.Fprintf(f,"hello")
    }
    

    The benefit over try-catch-finally is that there is no nesting of blocks and variable scopes. This simplifies the structure of the surrounding function.

    Just like finally blocks, deferred function calls can also modify the return value if they can reach the returned data.

    func yes() (text string) {
        defer func() {
           text = "no"
        }()
        return "yes"
    }
    
    func main() {
        fmt.Println(yes())
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 关于#vscode#的问题:ESP32开发板对接MQTT实现小灯泡的开关
  • ¥15 TMC2209串口模式下读取不到寄存器的值串口助手蓝色字体是发过去的消息,绿色字体是收到的消息,第二行发送读取寄存器的指令但是没有读取到寄存器的值串口助手如下图:接线如下图,如何解决?
  • ¥15 高通安卓11提取完整线刷包软件,或者优博讯dt50顺丰刷机包
  • ¥20 C,有个译码器,换了信道就跑不出原来数据
  • ¥15 MIMIC数据库安装问题
  • ¥60 基于JTag协议开发Fpga下载器上位机,哪位大🐂有偿指导?
  • ¥20 全书网Java爬取数据
  • ¥15 怎么获取红包封面的原始链接,并且获取红包封面序列号
  • ¥100 微信小程序跑脚本授权的问题
  • ¥100 房产抖音小程序苹果搜不到安卓可以付费悬赏