1. 程式人生 > >Go/流程控制/defer-延遲呼叫

Go/流程控制/defer-延遲呼叫

## defer

延遲呼叫,函式結束前執行

先進後出

異常發生後,前面的defer語句依舊會執行

常作 資源清理、異常處理

package main

import "fmt"

func test(x int){
	a := 1 / x
	a += a
}

func main(){
	fmt.Println("1111111")
	test(0)
	fmt.Println("2222222")
}

=======
1111111
panic: runtime error: integer divide by zero

goroutine 1 [running]:
main.test(...)
	E:/Code/Go/defer/main.go:6
func main(){
	defer fmt.Println("0000000")
	defer fmt.Println("1111111")
	test(0)
	defer fmt.Println("2222222")
}
===============
1111111
0000000
panic: runtime error: integer divide by zero
func main(){
	defer fmt.Println("0000000")
	defer fmt.Println("1111111")
	defer test(0)
	defer fmt.Println("2222222")
}
==========
2222222
1111111
0000000
panic: runtime error: integer divide by zero