It's much simpler than that. It's just a way of defining cleanup functions without having a language-level concept of destructors. Here's an example: https://gobyexample.com/defer.
This simple example should explain everything:
package main
import "fmt"
func function1() {
defer fmt.Println("function1: defer a")
fmt.Println("function1: inside")
defer fmt.Println("function1: defer b")
}
func main() {
fmt.Println("main: before function1")
function1()
fmt.Println("main: after function1")
}
Here is the output:
main: before function1
function1: inside
function1: defer b
function1: defer a
main: after function1
All defers run in LIFO order at the point when a function returns before the function returns execution back to the caller.
This simple example should explain everything:
Here is the output: All defers run in LIFO order at the point when a function returns before the function returns execution back to the caller.