在golang中使用延迟 [英] Use of defer in golang

查看:710
本文介绍了在golang中使用延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

golang中 defer 的用途是什么?语言文档说它在周围函数返回时执行。为什么不把代码放在给定函数的末尾?

解决方案

我们使用 defer 通常关闭或取消分配资源。它保证在任何情况下运行。遇到任何回报或恐慌。



此外,一个缓存的函数调用可以通过调用 recover 内置函数。这不能由最后的函数完成。



你可以把它看作另一个 try-catch-finally blocks。



完全相同 try-finally



< pre $ func main(){
f,err:= os.Create(file)
if err!= nil {
panic(can not创建文件)
}
推迟f.Close()
//不管这里发生什么文件都将被关闭
//为了简单起见,我跳过检查close结果
fmt.Fprintf(f,hello)
}

处理相同 try-catch-finally

  func main(){
defer func(){
msg:= recover()
fmt.Println(msg)
}()
f,err:= os.Create(。 )//。当前目录
if err!= nil {
panic(无法创建文件)
}
推迟f.Close()
//不管是什么这里发生的文件将被关闭
//为简单起见,我跳过检查关闭结果
fmt.Fprintf(f,hello)
}

与try-catch-finally相比,好处是没有块和变量作用域的嵌套,简化了函数的结构。 b
$ b

如果到达返回的数据,延迟函数调用也可以修改返回值。

  text =no
}()
returnyes
}

func main(){
fmt.Println(yes())
}


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

解决方案

We use defer to close or deallocate resources usually. It is guaranteed to run in every case. In case of any return or panic. You don't have this guarantee when you just place the function at the end.

Moreover a deffered function call can handle panic by calling recover builtin function. This cannot be done by function at the end.

You can think of it as another implementation of try-catch-finally blocks.

Closing alike 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 alike 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 blockes and variable scopes that simplifies structure of the function.

Alike finally blocks, deferred function calls can also modify returned value if the reach the returned data.

func yes() (text string) {
    defer func() {
       text = "no"
    }()
    return "yes"
}

func main() {
    fmt.Println(yes())
}

这篇关于在golang中使用延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆