Use of defer in Go

前端 未结 6 1581
谎友^
谎友^ 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 12:53

    Summary:

    When we do certain operations that need cleanup, we can "schedule" the cleanup operations which would be run when the function returns no matter which path that happens, including due to panic.

    Detailed answer:

    1. Programming languages strive to provide constructs that facilitate simpler and less error-prone development. (E.g. why should Golang support garbage collection when we can free the memory ourselves)
    2. A function can return at multiple points. The user might overlook doing certain cleanup operations in some paths
    3. Some cleanup operations are not relevant in all return paths
    4. Also, it is better to keep the cleanup code closer to the original operation which needed the cleanup
    5. When we do certain operations that need cleanup, we can "schedule" the cleanup operations which would be run when the function returns no matter which path that happens.

提交回复
热议问题