Use of defer in Go

前端 未结 6 1590
谎友^
谎友^ 2020-12-13 12:45

What is the use of defer in Go? The language documentation says it is executed when the surrounding function returns. Why not just put the code at end of given

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-13 13:01

    Key benefit of using defer - it will be called any way no matter how function will return. If an extraordinary situation would occur deferred function will be called.

    So it gives nice things:

    1. Recover after panic. This allows yes realize try ... catch behavior.

    2. Not to forget clean up (close files, free memory, etc) before normal exit. You may open some resource and you have to close it before exit. But function can have several exit points - so you have to add freeing in every return point. That’s very tedious in maintenance. Or you can put only one deferred statement - and resources will be released automatically.

提交回复
热议问题