go defer

defer is Last In First Out. the below func prints out: 4 3 2 1

func a() {
	for i := 0; i < 5; i++ {
		defer fmt.Printf(i)
	}
}

defer is evaluated AFTER return statement.

func a() (i int) {
	defer func() { 
		fmt.Println(i) // prints 1
		i++ 
	}() // expression in defer must be function call
	return 1
}
func main() {
	fmt.Println(a()) // prints 2
}

  • given the above code, the func returned value is named i
  • when the func returns, i is 1
  • after the func returns, defer is called, 1 is printed
  • the value received by main is 2

“Deferred function may read and assign to the returning function’s named returned value” Defer, Panic, and Recover - The Go Programming Language

up

go

down

reference