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.