defer 關鍵字 首先來看官網的定義: A "defer" statement invokes a function whose execution is deferred to the moment the surrounding function returns, either because ...
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()
通過之前我們講的概念和重點,我們大概也知道輸出的是什麼了。結果我就不放了,大家看到了這篇文章就自己動手去試試吧。