8 coding hacks for Go that I wish I’d known when I started

Andrew Hayes
Level Up Coding
Published in
6 min readApr 27, 2021

--

If you’re looking for Go coding hacks, I’ve got you covered! After years of working with Go, I’ve stumbled upon some nifty tips and tricks that have significantly improved my coding experience. Here’s one that might come in handy:

1. Checking if a key is in a map

Do you ever need to check if a key is present in a map? Here’s a quick and efficient way to do it:

_, keyIsInMap := myMap["keyToCheck"]
if !keyIsInMap {
fmt.Println("key not in map")
}

2. Check when casting a variable.

As a Go programmer, you may need to convert variables from one type to another. However, mistyping the type can lead to a panicked code. For instance, consider this code that tries to cast the “data” variable to a string:

value := data.(string)

If “data” cannot be cast to a string, your code will panic. Fortunately, there’s a better way to handle type conversions! Just like checking if a key exists in a map, you can verify if a cast was successful by using a boolean value.

value, ok := data.(string)

Here, the boolean “ok” indicates whether the cast was successful or not. By using this technique, you can gracefully handle type mismatches instead of encountering a panicked code.

3. Specify the size of the array when using append.

If you’re working with arrays in Go, you might have used the “append” function to add items to an array. Here’s an example:

for _, v := range inputArray {
myArray = append(myArray, v)
}

However, this approach can be slow when dealing with large arrays, as “append” keeps increasing the size of the array. A better method is to specify the length of the array and assign values directly:

myArray := make([]int, len(inputArray))
for i, v := range inputArray {
myArray[i] = v
}
}

Another technique, which I prefer and find more readable, combines the previous two methods. It also has the benefit of not incurring the speed penalty because the size is set at the start.

--

--