Simple Go defer code example

January 10, 2021 1 By addshore

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 ;)