5 ms·
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://go
by cyphar 9y ago
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 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.
- 19eightyfour 9y agoGot it thanks a lot, that's very clear.