Go - defer

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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • If In Go a simple if looks like this: Mandatory braces en...
    指北閱讀 231評(píng)論 0 0
  • 標(biāo)簽(空格分隔): 編程 Go官方文檔 Using the tour 1.1 Hello, 世界 Welcome...
    uangianlap閱讀 1,639評(píng)論 0 5
  • 一、什么是defer? defer是Go語(yǔ)言提供的一種用于注冊(cè)延遲調(diào)用的機(jī)制:讓函數(shù)或語(yǔ)句可以在當(dāng)前函數(shù)執(zhí)行完畢后...
    愛情小傻蛋閱讀 514評(píng)論 0 0
  • golang中defer,panic,recover是很常用的三個(gè)特性,三者一起使用可以充當(dāng)其他語(yǔ)言中try…ca...
    smoke_zl閱讀 27,945評(píng)論 2 28
  • 1 官方定義 A defer statement pushes a function call onto a li...
    Love語(yǔ)鬼閱讀 1,181評(píng)論 0 3

友情鏈接更多精彩內(nèi)容