defer_dbconn.go 856 B

123456789101112131415161718192021222324252627282930313233343536
  1. // defer_dbconn.go
  2. package main
  3. import "fmt"
  4. func main() {
  5. doDBOperations()
  6. }
  7. func connectToDB() {
  8. fmt.Println("ok, connected to db")
  9. }
  10. func disconnectFromDB() {
  11. fmt.Println("ok, disconnected from db")
  12. }
  13. func doDBOperations() {
  14. connectToDB()
  15. fmt.Println("Defering the database disconnect.")
  16. defer disconnectFromDB() //function called here with defer
  17. fmt.Println("Doing some DB operations ...")
  18. fmt.Println("Oops! some crash or network error ...")
  19. fmt.Println("Returning from function here!")
  20. return //terminate the program
  21. // deferred function executed here just before actually returning, even if there is a return or abnormal termination before
  22. }
  23. /* Output:
  24. ok, connected to db
  25. Defering the database disconnect.
  26. Doing some DB operations ...
  27. Oops! some crash or network error ...
  28. Returning from function here!
  29. ok, disconnected from db
  30. */