How does defer and named return value work?

后端 未结 3 1296
佛祖请我去吃肉
佛祖请我去吃肉 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:51

    According to the Go Specification:

    Return Statements A "return" statement that specifies results sets the result parameters before any deferred functions are executed.

    Defer Statements "...deferred functions are invoked immediately before the surrounding function returns..."

    So yes, as you assumed, the named return variable is assigned, then the deferred statement increments it.

    I would add that named return parameters can lead to subtle bugs, and generally should be avoided unless there's no alternative.

提交回复
热议问题