golang延时,在golang中使用延迟

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())

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值