Golang Best Practices - "defer"?

Golang Best Practices - "defer"

In Go, the "defer" keyword allows a function to postpone the execution of a statement until the surrounding function has completed. The deferred statement is executed before the function that contains the defer statement returns. This can be useful for cleaning up resources, such as closing a file or unlocking a mutex, after they are no longer needed. A defer statement can also be used to execute code regardless of whether a function returns normally or through a panic.

How Defer Works?

  • In Go, when a function encounters a defer statement, it schedules the execution of the deferred function call but continues with the rest of the function. The deferred function call is not executed immediately, but only after the function that contains the defer statement has completed and all other deferred function calls have been executed.
  • The deferred function calls are executed in Last-In-First-Out (LIFO) order, meaning that the last defer statement encountered is executed first, followed by the second-last, and so on. This allows developers to make sure that resources are cleaned up in the reverse order they were acquired.
  • Defer statements can be useful in situations where a function needs to clean up resources, such as closing a file, releasing a lock, or logging information. The defer statement ensures that the resource is cleaned up, even if the function returns early due to an error or panic.
  • It's important to keep in mind that deferred function calls should be simple and quick, and avoid heavy processing to ensure good performance. Additionally, deferred statements should be placed near to the point they are related to, to make the code easier to read and understand.

Best Practices Using Defer in Golang

  1. Defer statements should be placed near to the point they are related to, so code is easier to read.
  2. Defer function calls should be simple and quick, avoid heavy processing to keep performance.
  3. Defer statements should be used to clean up resources, such as closing a file or unlocking a mutex.
  4. Avoid using defer statements in loops, as it can cause unintended behavior and increase memory usage.
  5. If a function has multiple defer statements, they are executed in Last-In-First-Out (LIFO) order.
  6. Use panic and recover with care, only in situations where it makes sense to handle errors using defer.


Edgardo Rodriguez

Front End Developer | Back End Developer | Content Creator

1 年

Great explanation about "defer" I was loking information about it to go depeer in my Go knowledge.

回复

要查看或添加评论,请登录

Radhakishan Surwase的更多文章

社区洞察

其他会员也浏览了