Ad Code

Defer Function in Golang

   

 Hello friends! In this post, I will be discussing about defer function in Golang. There are three points that are very important about defer function.

1. defer function waits for the surrounding function to complete.

2. defer function does not wait for functions present in other goroutines to complete its execution.

3. defer functions execute in the LIFO order.

    Now, let us understand each of these points in detail. First of all, let us understand the first point:

defer function waits for the surrounding function to complete. What does it mean? To understand this, let us write following code in main.go and run go run main.go command to run the program.

package main

import "fmt"

func echoStr(msg string) {
fmt.Println(msg)
}

func main() {
echoStr("msg 1")
echoStr("msg 2")
}

    You will see the following result:

msg 1

msg 2

    Now, let us modify the above code and prepend defer keyword before echoStr("msg 1").

package main

import "fmt"

func echoStr(msg string) {
fmt.Println(msg)
}

func main() {
defer echoStr("msg 1")
echoStr("msg 2")
}

If you run above program, you will see the following result:

msg 2
msg 1

We can see, msg 2 has been printed before msg 1. It is because, we are using defer keyword before echoStr("msg 1"). So, it becomes defer function and hence wait for the

surrounding function echoStr("msg 2") to complete its execution.

    Here, One thing is very important to note that, surrounding means function block. So, if a

defer function is present inside a if block, it will wait not only for the functions available inside

the if block to complete its execution; but also, it will wait for the functions outside that if block

but inside the functional block to complete its execution.


package main

import "fmt"

func echoStr(msg string) {
fmt.Println(msg)
}

func main() {
if (2 > 1) {
defer echoStr("msg 1")
echoStr("msg 3")
}
echoStr("msg 2")
}

    If we run the above program, we will get the following result:
msg 3 msg 2 msg 1

    Now let us come to the second point:

defer function does not wait for functions present in other goroutines to complete its execution.
To understand this, let us take a look at below program:

package main

import "fmt"

func echoStr(msg string) {
fmt.Println(msg)
}

func main() {
defer echoStr("msg 1")
echoStr("msg 2")
go echoStr("msg 3")
}

The result of the above program is:
msg 2 msg 1

Here, defer echoStr("msg 1") does not wait for echoStr("msg 3") to

complete its execution which is present in other goroutine.


    Now come to the last point:

defer functions execute in the LIFO order.

If we have more than one defer functions, then, the defer function called at last, will execute at first. Let us understand it with an example:

package main

import "fmt"

func echoStr(msg string) {
fmt.Println(msg)
}

func main() {
defer echoStr("msg 2")
defer echoStr("msg 1")
}
    The result of the above program is:
msg 1 msg 2