packagemainimport"fmt"funcmain() {function1()}funcfunction1() { fmt.Printf("In function1 at the top\n")deferfunction2() fmt.Printf("In function1 at the bottom!\n")}funcfunction2() { fmt.Printf("Function2: Deferred until the end of the calling function!")}
输出:
In Function1 at the top
In Function1 at the bottom!
Function2: Deferred until the end of the calling function!
请将 defer 关键字去掉并对比输出结果。
使用 defer 的语句同样可以接受参数,下面这个例子就会在执行 defer 语句时打印 0:
funca() { i :=0defer fmt.Println(i) i++return}
当有多个 defer 行为被注册时,它们会以逆序执行(类似栈,即后进先出):
funcf() {for i :=0; i <5; i++ {defer fmt.Printf("%d ", i) }}
// open a database connection deferdisconnectFromDB()
合理使用 defer 语句能够使得代码更加简洁。
以下代码模拟了上面描述的第 4 种情况:
packagemainimport"fmt"funcmain() {doDBOperations()}funcconnectToDB() { fmt.Println("ok, connected to db")}funcdisconnectFromDB() { fmt.Println("ok, disconnected from db")}funcdoDBOperations() {connectToDB() fmt.Println("Defering the database disconnect.")deferdisconnectFromDB() //function called here with defer fmt.Println("Doing some DB operations ...") fmt.Println("Oops! some crash or network error ...") fmt.Println("Returning from function here!")return//terminate the program// deferred function executed here just before actually returning, even if// there is a return or abnormal termination before}
输出:
ok, connected to db
Defering the database disconnect.
Doing some DB operations ...
Oops! some crash or network error ...
Returning from function here!
ok, disconnected from db