[Go] Tour: defar 心得筆記
defer 是 golang 的一個特色功能, 在 A Tour of Go 裡的說明如下:
Defer A defer statement defers the execution of a function until the surrounding function returns. The deferred call's arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.
之前在 defer 使用上, 主要是用函數結束前進行 io.Close
之類的必要結束動作.
或是替代其他語言中 try… catch … finally…
的 finally
.
仔細了解後才發現 defer 的一些特性, 使用上該多注意.
執行順序
defer 生效順序
defer 執行順序是先進後出, 如下:
func main() {
for i := 0; i < 5; i++ {
defer fmt.Printf("%d\n", i)
}
}
4
3
2
1
0
若透過 defer 呼叫處理的函數有順序關係, 使用上需注意實際執行順序.