funcconnectToDB() { fmt.Println("ok, connected to db") }
funcdisconnectFromDB() { fmt.Println("ok, disconnected from db") }
funcdoDBOperations() { connectToDB() fmt.Println("Defering the database disconnect.") defer disconnectFromDB() //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 }
输出:
1 2 3 4 5 6
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