← 返回刚才阅读的位置

知识卡片

普通读书笔记卡 · 4545.g.8.g

延迟调用负责退出清理

理解等级:中级

defer把函数调用安排在外围函数退出前执行,多项延迟调用按后进先出顺序运行,适合把资源清理放在获得资源附近。补充实现提醒:先检查资源创建是否成功,再登记相应清理;不要机械复制原书在错误检查前登记关闭的示例。defer也不等于程序强制退出时必然执行。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Go Language Foundations · 查看原书依据

      If multiple defer calls are used in a function, each is pushed onto a stack. When the surrounding function returns, the deferred calls are executed in last-in-first-out order. For example: func main() { defer fmt.Println("world") defer fmt.Println("cruel") defer fmt.Println("goodbye") } The above function, when run, will output the following: goodbye cruel world Pointers as Parameters

    参考来源

    - 位置:《Cloud Native Go》第03章《Go Language Foundations》(来源项目book-sources;源文件:extracted/Cloud Native Go (Matthew A. Titmus)/_epub-src/OEBPS/ch03.xhtml) - 结论依据:defer把函数调用安排在外围函数退出前执行,多项延迟调用按后进先出顺序运行,适合把资源清理放在获得资源附近。原文相应定义、示例或限制为此结论提供依据;补充纠错与版本边界在正文就近标明。 - 原始内容:If multiple defer calls are used in a function, each is pushed onto a stack. When the surrounding function returns, the deferred calls are executed in last-in-first-out order. For example: func main() { defer fmt.Println("world") defer fmt.Println("cruel") defer fmt.Println("goodbye") } The above function, when run, will output the following: goodbye cruel world Pointers as Parameters