[Go] Defer keyword
defer
make sure the operation will be executed at the end of a function.
func loadChampions() ([]champion, error) {
file, err := os.Open("tft_champions.json")
if err != nil {
return nil, err
}
defer file.Close()
var champions []champion
for {
if err := json.NewDecoder(file).Decode(&champions); err == io.EOF {
break
} else if err != nil {
return nil, err
}
}
return champions, nil
}
Notice that even we write defer file.Close()
after os.Open
, it doesn't mean it will close the file right away, file will be close by the end of the function.
Key Points about defer
:
-
Resource Management: It's a best practice to use
defer
for closing files, network connections, or releasing other resources. This pattern helps prevent resource leaks, which can lead to performance issues or crashes due to exhausted resources. -
Order of Execution: If multiple
defer
statements are called within the same function, they are executed in the reverse order they were deferred. This LIFO (Last In, First Out) execution order is particularly useful when the order of operations for cleanup is important. -
Error Handling and Cleanup: In functions with complex error handling and multiple return points,
defer
ensures that cleanup actions are performed without needing to duplicate cleanup code before each return statement. -
Deferred Function Arguments: The arguments of a deferred function are evaluated when the
defer
statement is executed, not when the deferred function is actually called. This is an important distinction when deferring a call with arguments that may change later in the function. -
Panic Recovery:
defer
can also be used in conjunction with recovery from panics (unexpected errors), allowing a program to recover from an error state gracefully or to perform necessary cleanup before crashing.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2023-02-06 [Typescript] Global Scope
2023-02-06 [Typescript] Indexing an Object with Branded Types
2019-02-06 [TypeScript] Type Definitions and Modules
2019-02-06 [Tools] Add a Dynamic Tweet Button to a Webpage
2019-02-06 [Algorithm] Find Nth smallest value from Array
2018-02-06 [Javascript] Delegate JavaScript (ES6) generator iteration control
2017-02-06 [React] Use React.cloneElement to Extend Functionality of Children Components