Gopher

Defer statement in Golang

Published on 10 May 2020
Last Updated on 10 May 2020

A defer statement is used for executing statements after a function has returned its value.

It is also important to note that calls used in defer function calls are evaluated immediately however the defer is not called until function returns the value.

When the surrounding function returns a value then defer statement is executed.

This behaviour is demonstrated in the example given below:

package main

import "fmt"

func someFunction(){
	defer func() {
		fmt.Println("someFunction exited")
	}()

	fmt.Println("someFunction is called")
}

func main() {

	defer func() {
		fmt.Println("main exited")
	}()

	someFunction()
	fmt.Println("main is called")
}

Program output

Above program produces following output:

someFunction is called
someFunction exited
main is called
main exited

Program Description

In above program, someFunction and main functions have a defer statements. However in both cases, defer statements are executed only after function has returned its value. This is true even if defer statement is placed before other statements.

Stacking more than one defer statements

When a function has more than one defer statements, then defer statements are executed in last in first out order. This behaviour is demonstrated in the example given below.

package main

import "fmt"

func main() {
	defer fmt.Println("defer 1")
	defer fmt.Println("defer 2")
	defer fmt.Println("defer 3")
	defer fmt.Println("defer 4")
	defer fmt.Println("defer 5")
}

Program output

Above program produces following output:

defer 5
defer 4
defer 3
defer 2
defer 1