Golang
Using Functions
Defer Statement
In this lesson, we'll explore the defer statement in Go, a powerful feature that postpones a function’s execution until the surrounding function returns. While the arguments for a deferred function call are evaluated immediately, the function itself executes later. This behavior ensures that certain operations, such as resource cleanup, occur right before a function exits.

How the Defer Statement Works
Consider the example below with three functions: printName, printRollNo, and printAddress.
- The
printNamefunction outputs a provided string. - The
printRollNofunction prints an integer. - The
printAddressfunction prints a string representing an address.
Within the main function, the program flow is as follows:
- The
printNamefunction is immediately called to print the name "Joe". - The
deferkeyword schedules theprintRollNofunction to execute aftermainfinishes its other statements. - The
printAddressfunction is called to print the address "street-32". - Once
mainis ready to return, the deferredprintRollNo(23)call is executed.
Note
Even though the argument for printRollNo(23) is evaluated immediately, the deferred function call itself is executed only after the main function completes.
Example Code
Below is the complete Go code that demonstrates the usage of the defer statement:
package main
import "fmt"
// printName prints the provided name.
func printName(str string) {
fmt.Println(str)
}
// printRollNo prints the student's roll number.
func printRollNo(rno int) {
fmt.Println(rno)
}
// printAddress prints the provided address.
func printAddress(addr string) {
fmt.Println(addr)
}
func main() {
printName("Joe")
defer printRollNo(23)
printAddress("street-32")
}
Running the Program
To execute the program, use the following command in your terminal:
go run main.go
The output will be:
Joe
street-32
23
Output Breakdown
printName("Joe")is executed immediately, displayingJoe.- The
defer printRollNo(23)statement schedulesprintRollNoto run after completion of themainfunction. printAddress("street-32")executes next, printingstreet-32.- When
mainis about to return, the deferred call toprintRollNo(23)is finally executed, printing23.
Additional Resources
For further details on Go's control flow and function execution, consider visiting these resources:
That concludes our discussion of the defer statement. Happy coding and enjoy exploring Go's powerful features with your own hands-on exercises!
Watch Video
Watch video content
Practice Lab
Practice lab