Understand how 'defer' works

Below is my go code and it goes into an infinite loop :-

  1 package main
  2 
  3 import "fmt"
  4 
  5 func main() {
  6    function1()
  7 }
  8 
  9 func function1() {
 10    fmt.Println("=====> FUNCTION 1 <=========")
 11    fmt.Println("Function1 called.  Deferring function2 execution for now")
 12    defer function2()
 13    //function2()
 14    fmt.Println("End of function1")
 15    fmt.Println("=====> FUNCTION 1 END <=========")
 16 }
 17 
 18 func function2() {
 19    fmt.Println("Deferring function3")
 20    defer function3()
 21    fmt.Println("Deferring function1")
 22    defer function1()
 23    fmt.Println("function2 called by function1 defer")
 24    fmt.Println("=====> FUNCTION 2 <=========")
 25 }
 26 
 27 func function3() {
 28    fmt.Println("function3 called by function2 defer")
 29    fmt.Println("=====> FUNCTION 3 <=========")
 30 }

My understanding is when line # 22 is called in the above code function1() has already exited. But this goes into an infinite loop and it did not execute function3 at all.

Any help to understand how ‘defer’ works is highly appreciated.

Hey @sudhe,

Deferred function calls are executed in Last In First Out order after the surrounding function returns.

so in your case you are never reaching the call to function3() and you get stuck in an infinite loop of function1 calling function2 and then function2 calling function1.

This page might help you understand defer a little bit better: https://blog.golang.org/defer-panic-and-recover.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.