Golang defer clarification

后端 未结 3 1767
迷失自我
迷失自我 2020-12-28 17:14

What happened when defer called twice when the struct of that method has been changed?

For example:

rows := Query(`SELECT FROM whatever`)
defer rows.         


        
3条回答
  •  梦毁少年i
    2020-12-28 17:59

    Effective Go mentions:

    The arguments to the deferred function (which include the receiver if the function is a method) are evaluated when the defer executes, not when the call executes.

    Besides avoiding worries about variables changing values as the function executes, this means that a single deferred call site can defer multiple function executions

    In your case, the defer would reference the second rows instance.
    The two deferred functions are executed in LIFO order (as mentioned also in "Defer, Panic, and Recover").

    As icza mentions in his answer and in the comments:

    The 2 deferred Close() methods will refer to the 2 distinct Rows values and both will be properly closed because rows is a pointer, not a value type.

提交回复
热议问题