Functions, Returns & Defer
Go functions are first-class citizens. They support multiple return values, named returns, and the defer keyword to manage resource cleanups.
1 Multiple Returns & The defer execution stack
Go functions provide two unique capabilities:
- Multiple Return Values: Functions can return multiple values, commonly used to return a result alongside an `error` flag.
- defer Keyword: Postpones the execution of a statement until the enclosing function completes. Deferred calls are pushed onto a Last-In-First-Out (LIFO) stack. This is highly useful for closing files or database streams, ensuring cleanup code runs even if exceptions occur.
2 Function Configurations Code
Let's run a program using multiple return functions and tracing deferred cleanup execution ordering:
Go — Multiple Returns & Defer
▶ Run Code
package main
import "fmt"
// Multiple return values
func divide(x, y int) (int, bool) {
if y == 0 {
return 0, false // division by zero is invalid
}
return x / y, true
}
func main() {
// 1. Trace defer LIFO stack (execution order: 2, then 1)
defer fmt.Println("Deferred print 1")
defer fmt.Println("Deferred print 2")
fmt.Println("Main function executing...")
// 2. Multiple returns
res, ok := divide(10, 2)
if ok {
fmt.Println("Result: ", res)
} else {
fmt.Println("Error occurred during division!")
}
}
3 Code Challenge
Challenge: Write a function called `getStats` that accepts a slice of integers and returns both the sum (int) and count (int) of its elements. Test it in `main()` and print both values.