Asset 31Asset 32
Navigate back to the homepage

The ,ok idiom

Sebastian Ojeda
September 16th, 2019 · 1 min read

Idiomatic programming refers to following the conventions of a language. When it comes to programming languages, Go is still considered fairly new, and yet it has already established patterns unique to the language. If you’ve spent some time staring at Go source code, you’ve probably noticed some of these patterns. For the sake of this article, I’d like to discuss one of the most common patterns: the ,ok (comma ok) idiom.

Before I begin, it’s also worth noting that idioms, while nice to follow, are much less important than working code, and as such, patterns are not meant to be a definitive guide. The Go language is constantly evolving and new best practices and idioms are always changing. With that said, let’s begin.

Ok comma?

Consider the following map of users to high scores in a game

1highScores := make(map[string]int)
2highScores["john"] = 23
3highScores["mary"] = 19
5log.Println(highScores) // logs [john:23 mary:19]

This seems simple enough. Now imagine you wanted to retrieve a user’s score from the map. You can simply try the following

1highScores := make(map[string]int)
2highScores["john"] = 23
3highScores["mary"] = 19
5log.Println(highScores["john"]) // logs 23, as expected

While this works in this example, what happens when you attempt to get the score of a user that does not exist? 🧐Turns out, Go returns the default zero value. In this case, the keys are of type int so Go will return 0. However, how do you differentiate between a user who’s score is zero and a user that does not exist? This is where the comma, ok idiom becomes apparent.

Best practice

The best practice, and one that you will see very often is the following

1highScores := make(map[string]int)
2highScores["john"] = 23
3highScores["mary"] = 19
5if val, ok := highScores["john"]; ok {
6 log.Println(val) // logs 23

This ensures that we are only using the retrieved value from our map, and not a zero value by mistake. If you would simply like to check the presence of a key in a map, you can use the blank identifier.

1_, ok := highScores["john"]

Go is full of cool little patterns and nuances that make the language extremely fun to write. Now, go write some awesome code.

More articles from Fullstack Go

Go Runtime Environment Variables

Ever wondered what the heck all the Go runtime environment variables meant? Not anymore.

October 27th, 2019 · 3 min read

Dockerize your Go Microservice

My favorite language and the world's most popular containerization platform come together in the most beautiful way.

September 30th, 2019 · 2 min read
© 2019 Fullstack Go
Link to $ to $