Created
February 7, 2018 13:28
-
-
Save tomtsang/f3cddfda6aec3ced5dd84da2fb4459a3 to your computer and use it in GitHub Desktop.
golang-func-defer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import "fmt" | |
| func main() { | |
| doDBOperations() | |
| } | |
| func connectToDB() { | |
| fmt.Println("ok, connected to db") | |
| } | |
| func disconnectFromDB() { | |
| fmt.Println("ok, disconnected from db") | |
| } | |
| func doDBOperations() { | |
| 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 | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment