Golang defer behavior

后端 未结 3 1454
孤独总比滥情好
孤独总比滥情好 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:20

    A little further down, the spec also explicitly says that parameters are evaluated at the time the defer statement runs, not at return/panic time when the deferred function is actually called:

    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.

    And yes, it can definitely be confusing that the parameters are evaluated at one time and the function body runs at another. I've been caught by it.

提交回复
热议问题