Defer Keyword in Go

Defer Keyword in Go

Greetings folks,

In this article, we are going to see the use of defer keyword in Go.

In simple words, to schedule the execution of a function after other functions have been executed defer is used.

package main
import "fmt"

func main() {
    fmt.Println("start")
    defer fmt.Println("defer keyword")    
    fmt.Println("done")
}

OUTPUT:

start
done
defer keyword

As you can see from the above example, the defer statement is executed after the 2 other statements have been executed.

But now the question arises how would the execution take place if there are multiple defer statements?

Defer follows the LIFO(Last In First Out) order which you might be familiar with if you have studied Stacks in Data Structures.

To understand this better check out the code snippet below

package main
import "fmt"

func printOne(){
    fmt.Println(1)
}

func printTwo(){
    fmt.Println(2)
}

func printThree(){
    fmt.Println(3)
}

func main() {
    fmt.Println("start")

    defer printOne()
    defer printTwo()
    defer printThree()

    fmt.Println("done")
}

OUTPUT:

start
done
3
2
1

As you can see printThree() is executed first among the defer statements since it is the last one to go in the call stack, while printOne() is executed last since it is the first one to go in the call stack.

And that's it for the article, hopefully, you learned something new. Tell me your thoughts about this article in the comments.