Golang defer behavior

后端 未结 3 1459
孤独总比滥情好
孤独总比滥情好 2020-11-28 06:40

Effective Go states the following regarding defer:

The arguments to the deferred function (which include the receiver if the function is a method) are

3条回答
  •  感动是毒
    2020-11-28 07:29

    That seems coherent (see also "Defer, Panic, and Recover")

    Deferred function calls are executed in Last In First Out order after the surrounding function returns.

    This function prints "3210":

    func b() {
        for i := 0; i < 4; i++ {
            defer fmt.Print(i)
        }
    }
    

    The last call when the defer is evaluated means i=3, the previous to last means i=2 and so on.

    Golang spec:

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


    the defers will be called when func ends

    yes, but their arguments are evaluated before, while the loop is running.

    You have a trickier defer case in "How golang's “defer” capture closure's parameter?" when used with closure (function literal), as detailed in "Why add “()” after closure body in Golang?".

提交回复
热议问题