This repository demonstrates the usage of multiple defer
statements in Go, showcasing how they are executed in a Last In, First Out (LIFO) order. The defer
keyword is commonly used to schedule tasks such as resource cleanup that should occur after the surrounding function completes.
- This example covers the usage of multiple `defer` statements in Go.
- It shows how the `defer` statements are executed in reverse order (LIFO) after the main function completes.
package main
import (
"fmt"
)
func main() {
// multiple defer statements are used, they are executed in Last In, First Out (LIFO) order
defer fmt.Println("First defer")
defer fmt.Println("Second defer")
defer fmt.Println("Third defer")
fmt.Println("Executing main function")
}
-
Make sure you have Go installed. If not, you can download it from here.
-
Clone this repository:
git clone https://github.com/Rapter1990/go_sample_examples.git
-
Navigate to the
027_panic_and_defer/002_multiple_defer
directory:cd go_sample_examples/027_panic_and_defer/002_multiple_defer
-
Run the Go program:
go run main.go
When you run the program, you should see the following output:
Executing main function
Third defer
Second defer
First defer