Intermediate 16 min readModule: Module 5: Functions, Multiple Returns & Named Returns
Multiple Return Values & The 'defer' Statement
Return multiple values (result, error) and guarantee resource cleanup with LIFO 'defer' statements.
What You Will Learn in This Lesson
- Functions returning multiple values (value, error)
- The 'defer' statement for guaranteed cleanup before function exit
- LIFO (Last In, First Out) execution order of multiple defers
Introduction & Core Concept
Go functions can return any number of results. The 'defer' keyword schedules a function call to run immediately before the enclosing function returns.
WHY DOES THIS MATTER IN THE REAL WORLD?
Placing 'defer file.Close()' immediately after opening a file guarantees the file descriptor closes, preventing leaks.
Multiple Returns & Defer Cleanup
gogo
1234567891011121314151617package mainimport "fmt"func divide(a, b float64) (float64, error) {if b == 0 {return 0, fmt.Errorf("division by zero")}return a / b, nil}func main() {defer fmt.Println("Cleanup: Execution completed.")res, err := divide(100, 4)if err == nil {fmt.Println("Result:", res)}}
Line-by-Line Technical Breakdown
1Defer statements evaluate their arguments immediately when encountered.
Try It Yourself (Interactive Editor)
Modify the code in real-time and click Run to test live browser output and console logs.
Intelligent Code Runner & Live Sandbox[GO]
GO SOURCE EDITOR
Interactive Live CodeIndustry Best Practices & Professional Standards
- Always pair resource acquisition (opening files/locks) with an immediate defer cleanup.
Lesson Summary & Core Takeaways
- Multiple returns and defer make resource management explicit and clean.