defer 關鍵字
首先來看官網的定義:
A "defer" statement invokes a function whose execution is deferred to the moment the surrounding function returns, either because the surrounding function executed a return statement, reached the end of its function body, or because the corresponding goroutine is panicking.
就是被標記了 defer 的片段會呼叫一個函式,這個函式會推遲在周圍函式執行完回傳后執行,要注意,在最后的說明中還帶有 panicking,這是什么呢?
看了官網檔案對 panicking 的解釋,我認為是就是一個運行期的未知的例外處理程式,比如陣列越界就會觸發一個 run-time panic,就相當于呼叫內置函式 panic,并用實作了介面型別 runtime-Error 的值做為引數,觸發這個錯誤就代表著它是未確定的錯誤,
defer 呼叫的格式為
DeferStmt = "defer" Expression . // Expression 必須是方法或函式
這里面有個很重要點:
Each time a "defer" statement executes, the function value and parameters to the call are evaluated as usual and saved anew but the actual function is not invoked. Instead, deferred functions are invoked immediately before the surrounding function returns, in the reverse order they were deferred.
每次一個 defer 陳述句呼叫,這個普通函式值和引數會被(重點)重新保存,但是實際上并沒有呼叫,而是在環繞函式回傳之前立即呼叫,(重點來了)并且會將標記的 defer 的執行的順序反轉再呼叫,
舉個例子:
// out func
func f() (result int) {
defer func() {
result *= 7
}()
return 6
}
for i := 0; i <= 3; i++ {
defer fmt.Println(i)
}
fmt.Println("==================")
f()
通過之前我們講的概念和重點,我們大概也知道輸出的是什么了,結果我就不放了,大家看到了這篇文章就自己動手去試試吧,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/38584.html
標籤:Go
上一篇:go實作java虛擬機03
下一篇:gopm的使用和更新go語言
