Learn to identify and fix the most frequent mistakes in Golang.
One of the common mistakes in Go is the lack of error handling. It is important to always check for errors when working with potentially faulty values. Use the error type to verify if an error has occurred and handle it appropriately.
file, _ := os.Open("nonexistent.txt") // β Ignoring error
fmt.Println(file.Name()) // β May cause a panic!
panic(errors.New("something went wrong")) // β Bad practice
file, err := os.Open("nonexistent.txt")
if err != nil {
fmt.Println("Error:", err) // β
Proper error handling
return
}
func divide(a, b int) (int, error) {
if b == 0 {
return 0, errors.New("division by zero") // β
Return meaningful error
}
return a / b, nil
}
errors.Is
for better error handling.if errors.Is(err, ErrPermissionDenied) {
fmt.Println("Access denied.") // β
Handling specific error
}
One of the most common mistakes in Go is forgetting to release resources such as files, network connections, or database queries after using them. This can lead to memory leaks, resource exhaustion, or unexpected behavior in your program.
defer
is a built-in keyword in Go that postpones the execution of a function
until the surrounding function returns. It is commonly used to ensure that resources are properly released when
a function completes.
func openFile() {
file, err := os.Open("data.txt")
if err != nil {
fmt.Println("Error opening file:", err)
return
}
file.WriteString("Hello, Go!") // β File might remain open
}
defer
to Ensure Closurefunc openFile() {
file, err := os.Open("data.txt")
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer file.Close() // β
Ensures closure
file.WriteString("Hello, Go!")
}
defer
func queryDatabase() {
db, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/dbname")
if err != nil {
log.Fatal(err)
}
defer db.Close() // β
Ensures database connection is closed properly
}
var mu sync.Mutex
func safeIncrement() {
mu.Lock()
defer mu.Unlock() // β
Ensures the mutex is unlocked even if an error occurs
// Critical section
}
func sendResponse(w http.ResponseWriter) {
w.Write([]byte("Processing request..."))
defer w.Write([]byte("Response completed.")) // β
Ensures this message is always written
}
defer
While defer
is useful, there are cases where you should avoid it for performance reasons:
defer
statements accumulate, causing performance issues.for i := 0; i < 1000; i++ {
file, _ := os.Open("file.txt")
defer file.Close() // β BAD: This will create 1000 deferred function calls!
}
for i := 0; i < 1000; i++ {
file, _ := os.Open("file.txt")
file.Close() // β
Close it immediately after usage
}
π Thank you for reading these articles! If you find this content valuable and want to support my work, a coffee would be greatly appreciated! βπ
π» I am a freelance web developer, and I personally create and maintain this website. Any support would help me improve and expand it further! π