Defer

Defer causes a function to be executed when the function where defer was called returns.

You can call defer more than once inside a function. Thus, the functions will be stacked, and this will be their execution order before the main return.


func addup(x, y int) int {
    // The print function will be called
    // right before the return
    defer fmt.Println(x, "+", y)

    result := x + y
    return result
}
                        
defer.go