美文网首页
Go - defer

Go - defer

作者: 隐号骑士 | 来源:发表于2024-12-21 22:22 被阅读0次

Go's defer statement schedules a function call (the deferred function) to be run immediately before the function executing the defer returns. It's an unusual but effective way to deal with situations such as resources that must be released regardless of which path a function takes to return. The canonical examples are unlocking a mutex or closing a file.

package main

import "fmt"

func main() {
    defer fmt.Println("This is the last statement in main.") 

    fmt.Println("Starting main...")

    defer fmt.Println("This is the second deferred statement.") 

    fmt.Println("End of main.")
}

output:

// LIFO
Starting main...
End of main.
This is the second deferred statement.
This is the last statement in main.

The arguments to the deferred function (which include the receiver if the function is a method) are evaluated when the defer executes, not when the call executes.

package main

import "fmt"

func main() {
    i := 0
    defer fmt.Println(i)
    i++
}

output:

0

相关文章

  • golang defer 特性

    defer.go

  • Go Defer

    Go Defer 如果函数里面有多条defer指令,他们的执行顺序是反序,即后定义的defer先执行。 defer...

  • Go教程第二十七篇:Defer

    Defer 本文是《Go系列教程》的第二十二篇文章。 什么是Defer? defer/dɪˈfɜː(r)/ 意为:...

  • goLang异常处理

    defer defer是go提供的一种资源处理的方式。defer的用法遵循3个原则在defer表达式被运算的同时,...

  • Go language quick framework

    hello world structure syntax case defer go...

  • 异常

    1、error接口 2、defer 你可以在Go函数中添加多个defer语句,当函数执行到最后时,这些defer语...

  • go defer

    函数体执行结束后,按照调用顺序的反向,逐个执行 即时函数发生严重错误也会执行 支持匿名函数的调用 常用于自愿清理、...

  • defer go

    Go语言的 defer 语句会将其后面跟随的语句进行延迟处理,在 defer 归属的函数即将返回时,将延迟处理的语...

  • Go defer

    Outputs:

  • go/defer

    defer使用 defer是Go语言提供的一种用于注册延迟调用的机制:让函数或语句可以在当前函数执行完毕后(包括通...

网友评论

      本文标题:Go - defer

      本文链接:https://www.haomeiwen.com/subject/ykkeejtx.html