Saturday 4 September 2021

Go defer keyword

 The defer keyword is generally used for cleaning purpose. The defer keyword postpones the execution of a function or statement until the end of the calling function.

It executes code (a function or expression) when the enclosing function returns before the closing curly brace }. It is also executed if an error occurs during the execution of the enclosing function.

Go defer Example

  1. package main  
  2. import (  
  3.    "fmt"  
  4. )  
  5. func main() {  
  6.    defer print1("Hi...")  
  7.    print2("there")  
  8. }  
  9. func  print1(s string)  {  
  10.    fmt.Println(s)  
  11. }  
  12. func print2(s string)  {  
  13.    fmt.Println(s)  
  14. }  

Output:

there
Hi... 

No comments:

Post a Comment