
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.