Go defer function call

The defer statement defers the execution of a function until the surrounding function returns. The deferred call's arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.

Go defer function call

In the example, the sayHello function is called after the main function finishes.


package main

import "fmt"

func main() {

    fmt.Println("begin main")

    defer sayHello()

    fmt.Println("end main")
}

func sayHello() {

    fmt.Println("hello")
}

Output:

begin main
end main
hello

Comments