Skip to main content
Published on

Common Errors in Go

Share:

Introduction

Although Go is known for its simplicity and efficiency, like every programming language, it has quirks that can be a source of errors for developers. In this article, we explore some of these common errors to help you avoid pitfalls in your code.

1. Not handling returned errors

A classic mistake in Go is ignoring errors returned by functions.

res, _ := http.Get("https://api.example.com/data")

The right approach is to handle the error by checking it:

res, err := http.Get("https://api.example.com/data")

if err != nil {
  log.Fatalf("Error fetching data: %v", err)
}

2. Incorrect use of packages

Importing unnecessary packages or using packages that are not suitable for the task at hand are common mistakes.

import (
  "fmt"
  "math/rand"
)

func main() {
  fmt.Println(rand.Intn(100))  // May not be as random as you think!
}

3. Slices and their pitfalls

An inaccurate understanding of how slices work in Go can lead to unexpected behaviour.

a := []int{1, 2, 3}
b := a[:2]
b[0] = 42
fmt.Println(a)  // [42, 2, 3]

In this example, b is a slice of a, which means they share the same memory. When you modify b, you also modify a.

4. Goroutines and closures

When using goroutines with loops, it is common to encounter unexpected behaviour due to the use of closures.

for i := 0; i < 3; i++ {
  go func() {
    fmt.Println(i)
  }()
}

The output above may be surprising, as it can print the same number multiple times.

Conclusion

Go is a powerful and intuitive language, but, like all languages, it has its nuances. By familiarising yourself with these common errors, you will be better prepared to write more robust and effective Go code.

Happy coding!