Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
go
communitycreator

What is the defer keyword in Golang?

Shubham Singh Kshatriya

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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")
}
Using multiple defer keywords in code

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.

RELATED TAGS

golang
go
communitycreator

CONTRIBUTOR

Shubham Singh Kshatriya

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring