What is the defer keyword in Golang?

In Golang, the defer keyword is used to delay the execution of a function or a statement until the nearby function returns.

In simple words, defer will move the execution of the statement to the very end inside a function.

Syntax

defer fmt.PrintIn("Hello")

Code

package main
import "fmt"
func greet() {
defer fmt.Println("World")
fmt.Println("Hello")
}
func main() {
greet()
}

Explanation

If we invoke the greet() function, the compiler will go to defer fmt.Println("World") (line 5), but since it finds the defer keyword, it will not execute it until it reaches the end of the function. Thus, the compiler will move to fmt.Println("Hello") (line 6) and execute it first instead.

Multiple defer statements

Multiple defer statements are allowed in the same program and will be executed in the reverse order in which they were deferred. In other words, they will follow the LIFOLast-In, First-Out order.

Code

The code snippet below shows an example of multiple defer statements.

package main
import "fmt"
func main() {
defer fmt.Println("World")
defer fmt.Println("One")
defer fmt.Println("Two")
fmt.Println("Hello")
}

Output

In the above code, we add the defer keyword to three out of the four statements, as we can see in the console.

When we run the code, World, One, and Two will be pushed in a stack and will be executed in LIFO order before the function returns.