Top 10 Go Coding Traps

How to avoid them

Stefanie Lai
5 min readJun 25, 2021
From Unsplash, @Benjamin Elliott

Go is currently the most common programming language in cloud development. Though I use it very much in my work, I am still repeating certain mistakes. This article is more a record of these errors, figuring out the causes and solutions so that people who read this article will save themselves time when coming across the same problems.

Let’s cut through to the tips.

Don’t rely on index var in the for loop.

The most common mistake we make is that we often create goroutine inside a for loop and rely on the index variable. For example,

The code looks just right at first sight, while the output is always 4(the last value in the array). Why?

Because goroutines won’t start before the for loop finishes. And assigned with a new value(0,1,2,3) in each loop, the index is always 3 in the end.

To avoid it, you just stop relying on the index variable. Instead, you can either pass it into the goroutine or copy it to a new variable inside the loop…

--

--

Stefanie Lai
Stefanie Lai

No responses yet