Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Defer in if-statements

  • Even if we put the defer call inside an if-statement, the deferred function will only execute at the end of the enclosing function.
package main

import (
	"fmt"
)

func main() {
	if true {
		fmt.Println("Before")
		defer fmt.Println("Middle")
		fmt.Println("After")	
	}

	fmt.Println("Outside")
}