Skip to content

Instantly share code, notes, and snippets.

@tomtsang
Created February 7, 2018 13:28
Show Gist options
  • Select an option

  • Save tomtsang/f3cddfda6aec3ced5dd84da2fb4459a3 to your computer and use it in GitHub Desktop.

Select an option

Save tomtsang/f3cddfda6aec3ced5dd84da2fb4459a3 to your computer and use it in GitHub Desktop.
golang-func-defer
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