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.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.

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.
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.
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:Running the Program
To execute the program, use the following command in your terminal: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.