How does defer and named return value work?

后端 未结 3 1293
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-14 06:04

I just started learning Go and I got confused with one example about using defer to change named return value in the The Go Blog - Defer, Panic, and Recover.

The exam

3条回答
  •  隐瞒了意图╮
    2020-12-14 06:30

    A defer statement pushes a function call onto a list. The list of saved calls is executed after the surrounding function returns. -- The Go Blog: Defer, Panic, and Recover

    Another way to understand the above statement:

    A defer statements pushes a function call onto a stack. The stack of saved calls popped out (LIFO) and deferred functions are invoked immediately before the surrounding function returns.

     func c() (i int) {
        defer func() { i++ }()
        return 1
    }
    

    After 1 is returned, the defer func() { i++ }() gets executed. Hence, in order of executions:

    1. i = 1 (return 1)
    2. i++ (defer func pop out from stack and executed)
    3. i == 2 (final result of named variable i)

    For understanding sake:

     func c() (i int) {
        defer func() { fmt.Println("third") }()
        defer func() { fmt.Println("second") }()
        defer func() { fmt.Println("first") }()
    
        return 1
    }
    

    Order of executions:

    1. i = 1 (return 1)
    2. "first"
    3. "second"
    4. "third"

提交回复
热议问题