What is defer in Golang?

Defer

  • Very common when closing or releasing
defer fileReader.close()
defer dbReader.close()
defer httpConnection.close()
  • defer is executed in LIFO, so the last defer statement get executed first (very interesting!)
  • But delayed function call is only the function call after defer not including the function call that is inside the deferred function call
func trace(s string) string {
    fmt.Println("entering:", s)
    return s
}

func un(s string) {
    fmt.Println("leaving:", s)
}

func a() {
    defer un(trace("a"))
    fmt.Println("in a")
}

func b() {
    defer un(trace("b"))
    fmt.Println("in b")
    a()
}

func main() {
    b()
}

/*
entering: b
in b
entering: a
in a
leaving: a
leaving: b
*/