Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is golang defer statement execute before or after return statement?

Tags:

go

I have a question about golang defer: Is golang defer statement execute before or after return statement?

I have read Defer_statements. But I do not got the answer.

I made a simple test:

func test1() (x int) {
    defer fmt.Printf("in defer: x = %d\n", x)

    x = 7
    return 9
}

func test2() (x int) {
    defer func() {
        fmt.Printf("in defer: x = %d\n", x)
    }()

    x = 7
    return 9
}

func test3() (x int) {
    x = 7
    defer fmt.Printf("in defer: x = %d\n", x)
    return 9
}

func main() {
    fmt.Println("test1")
    fmt.Printf("in main: x = %d\n", test1())
    fmt.Println("test2")
    fmt.Printf("in main: x = %d\n", test2())
    fmt.Println("test3")
    fmt.Printf("in main: x = %d\n", test3())
}

In test1(), using Printfto print x after defer. In test2(), using a anonymous function to print x after defer. In test3(), using Printfto print x after defer, but defer after x = 7.

But the result is:

test1
in defer: x = 0
in main: x = 9
test2
in defer: x = 9
in main: x = 9
test3
in defer: x = 7
in main: x = 9

So, is any one can explain: 1. why got this result? why test1 prints 0, test2 print9, test3 prints 7. 2. is defer statement excutes after return or before return?

Thanks a lot.

like image 757
James Shi Avatar asked Oct 09 '18 09:10

James Shi


2 Answers

Thanks @dev.bmax @Tranvu Xuannhat @rb16. With your help, I found the key explanation from Defer_statements.

Each time a "defer" statement executes, the function value and parameters to the call are evaluated as usual and saved anew but the actual function is not invoked.

We can break up defer ... into three parts.

  1. invoke defer, evaluating the value of function parameter.
  2. execute defer, pushing a function in to stack.
  3. execute functions in stack after return or panic.

I made a new test4 to explain.

func test4() (x int) {
    defer func(n int) {
        fmt.Printf("in defer x as parameter: x = %d\n", n)
        fmt.Printf("in defer x after return: x = %d\n", x)
    }(x)

    x = 7
    return 9
}

In test4,

  1. invoke defer, evaluating the value of n, n = x = 0, so x as parameter is 0.
  2. execute defer, pushing func(n int)(0) onto stack.
  3. execute func(n int)(0) after return 9, n in fmt.Printf("in defer x as parameter: x = %d\n", n) has been evaluated, x in fmt.Printf("in defer x after return: x = %d\n", x) will be evaluated now, x is 9。

So, got the result:

test4
in defer x as parameter: x = 0
in defer x after return: x = 9
in main: x = 9
like image 66
James Shi Avatar answered Sep 22 '22 13:09

James Shi


As per the documentation of defer at golang.org,

Go's defer statement schedules a function call (the deferred function) to be run immediately before the function executing the defer returns.

The arguments to the defer statement are evaluated first, then moved to the defer stack and then executed before the enclosing function returns.

Example 1:

Syntax 1:

func display() (x int) {
    x = 10
    defer func() {
        fmt.Println(x)
    }()
    return 5
}

The above code can be re-written as,

Syntax 2:

func display() (x int) {
    x = 10
    defer func() {
        fmt.Println(x)
    }()
    x = 5
    // Deferred functions are executed.
    return
}

Result:

5

The variables passed to the anonymous functions from the enclosing function are passed by reference. The deferred function when it is being executed, takes the values held in that memory location at the time of execution.

like image 30
icemelting Avatar answered Sep 21 '22 13:09

icemelting