Simple Go defer code example
In Go, a defer statement will execute a function call just before the function it is called from returns.
I found that most of the examples of a Go defer call online seemed to do complicated things with numbers. So here is a nice simple example with just text output.
Example
You can run this code yourself in The Go Playground! You can also find a similar example in the Go Tour.
package main
import (
"fmt"
)
func main() {
// This will output first (in order)
fmt.Println("One")
// This will output last (before this function finishes)
defer fmt.Println("Two")
// This will be called before the above defer call "Two"
secondary()
}
func secondary() {
// This will output after Four (before this function finishes)
defer fmt.Println("Three")
// This will output (in order)
fmt.Println("Four")
}
Code language: JavaScript (javascript)
Output:
One
Four
Three
Two
If you get something else, you’re doing something wrong ;)
[…] can probably do some of this cleanup using defer, but I skipped that in this example for […]