My first go at Go
I’m going to be documenting my learning and projects on here and this week I’m learning Golang.
I’m choosing Go to learn because of its multiple uses and utility, as well as its usefulness in cryptocurrency and web3 applications - especially smart contracts as can be found on the ethereum blockchain.
My first tidbit about Go? defer
In Go (Golang), the defer statement is a powerful and unique feature that allows you to delay the execution of a function until the surrounding function completes. It is often used for tasks such as cleanup operations, resource deallocation, or ensuring certain actions are performed before exiting a function.
Why Defer?
1. Resource Cleanup:?
Consider scenarios where you need to open a file or establish a network connection. By using defer, you can ensure that the associated cleanup or closing operation happens regardless of how the function exits, whether it's due to normal return or an error.?
func processFile() error {
? ? ? file, err := os.Open("example.txt")
? ? ? if err != nil {
? ? ? ? ? return err
? ? ? }? ? ?
defer file.Close() // This is executed when processFile exits
? ? ? // File processing logic here
? ? ? // ...? ? ? return nil
? }
2. Simplifying Code:?
defer can make your code more readable by placing cleanup or finalization logic close to where resources are acquired or initialized.? This can be very useful for things like testing cleanup and closing database connections.
领英推荐
func complexInitialization() error {
? ? ?resource := acquireResource()? ? ?
defer releaseResource(resource) // Cleanup is deferred until the end
? ? ? // Complex initialization logic here
? ? ? // ...
? ? ? return nil
? }
3. Execution Order:?
Deferred functions are executed in a last-in, first-out (LIFO) order. This allows you to control the order of cleanup operations, ensuring that the most recently deferred function is executed first.
func multipleDefers() {
? ? ? defer fmt.Println("First")
? ? ? defer fmt.Println("Second")
? ? ? defer fmt.Println("Third")
? ? ? // Output: Third, Second, First
? }?
Example Usage:
Here's an example demonstrating defer in a practical scenario:
package main
import (
? ?"fmt"
? ?"os"
)
func main() {
? ?err := processFile("example.txt")
? ?if err != nil {
? ? ? ?fmt.Println("Error:", err)
?}}
func processFile(filename string)
error {
? ?file, err := os.Open(filename)
? ?if err != nil {
? ? ? ?return err
? ?}
? ?defer file.Close() // Ensures the file is closed when processFile exits
? ?// File processing logic here
? ?// ...? ?return nil
In this example, defer file.Close() guarantees that the file will be closed when the processFile function exits, regardless of the exit path.The defer statement in Go is a valuable tool for maintaining clean and organized code, especially when dealing with resource management. It enhances code readability and ensures that important actions are taken before a function exits, contributing to the robustness and reliability of your Go programs.
As a backend developer who has struggled with test cleanup and resource connections, this feature is great and makes readability and maintainability much easier on the developer.
ActiveCampaign Engineering Manager (prev. DocuSign, Apartments.com)
1 年Go is very pleasant. Enjoy. Only thing... error handling is a bit rough around the edges.