Go語言入門-延遲調用-defer
定義
func functionName([parameterList]) ([returnTypes]) {
defer statement
...
body
...
}
語句defer想當前函數註冊一個稍微執行的函數調用,它會在主調函數或者方法返回之前但是其返回值(當返回值存在)計算後執行。
- 存在多個defer語句採用後進先出LIFO(Last In First Out)的順序執行
- 主要用於釋放資源、解出鎖定、以及錯誤處理等場景。
- 示例1
簡單的展示defer函數調用
func main() {
defer fmt.Println("end")
fmt.Println("start")
}
/**
output:
start
end
*/
- 示例2
多個延遲出則按照FILO次序執行。
func main() {
defer fmt.Println("end")
defer fmt.Println("end end")
defer fmt.Println("end end end")
fmt.Println("start")
}
/**
output:
start
end end end
end end
end
*/
示例3
defer與閉包
func callClosure() func() int {
x := 10
return func()(y int) {
x++
fmt.Println(x)
return x
}
}
func main() {
//獲取callClosure函數返回的閉包函數
f := callClosure()
defer f() //註冊延遲調用f()-->f()帶狀態
fmt.Println("main: ", f()) //調用閉包函數,並打印返回值
//最後在執行延遲註冊的函數
}
/**
output:
11
main: 11
12
*/