0
0
Goprogramming~15 mins

Defer execution order in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Defer Execution Order in Go
📖 Scenario: Imagine you are writing a Go program that needs to clean up resources in a specific order after some operations. You want to learn how defer statements work and how their execution order is managed.
🎯 Goal: Build a Go program that uses multiple defer statements and prints messages to show the order in which deferred functions execute.
📋 What You'll Learn
Create a main function
Use multiple defer statements with print messages
Understand and demonstrate the LIFO (last-in, first-out) order of defer execution
Print the messages to show the order clearly
💡 Why This Matters
🌍 Real World
In real programs, defer is used to ensure resources like files or network connections are properly closed even if errors occur.
💼 Career
Understanding defer is important for writing clean, safe Go code especially in backend development, system programming, and cloud services.
Progress0 / 4 steps
1
Create the main function and initial print
Write a main function in Go that prints "Start of main".
Go
Hint

Use func main() to define the main function and println to print the message.

2
Add two defer statements with print messages
Inside the main function, add two defer statements that print "First defer" and "Second defer" respectively.
Go
Hint

Use defer println("message") to add deferred print statements.

3
Add a final print statement after defer statements
After the two defer statements, add a print statement that prints "End of main" inside the main function.
Go
Hint

Just add println("End of main") after the defer statements.

4
Run the program and observe the output
Run the program and print the output to see the order of execution of the print statements and deferred functions.
Go
Hint

Run the program using go run and observe that deferred functions run in reverse order.