Before Go 1.18, when you wanted to pull a list of keys from a map in Go, you had to write code that iterated over the map and added the keys to a slice. Since then, with the new Generics feature, you can write a single universal function that gets keys from any map and use it whenever you need it. No more writing code for a specific type of map 😉.
This article is part of the Introduction to Go Generics series. Go here to see more.
Along with the Go 1.18 release, the
golang.org/x/exp/maps
package has also been released, with theKeys()
function working the same as the one below.
|
|
The keys()
function takes a map as an argument, in which the keys are of the type with comparable
constraint, and the values, with any
constraint. As you may already know from our previous tutorial on Generics, the comparable
constraint describes types whose values can be compared, meaning that the ==
and !=
operators can be used on them. The any
constraint is equivalent to interface{}
- it accepts any type, so the values of a map can be anything.
The rest of the function is very simple. It returns a slice of keys []K
, so in the first line of the function body, the resulting slice is created. Notice that it has a capacity equal to the size of the map. Then, in a loop, each map key is added to the resulting slice. Running the example code with two different maps, you get the output:
vegetableSet keys: [potato cabbage carrot]
fruitRank keys: [1 2 3]
And that’s all. Now, with a single keys()
function, you can get a list of keys for any map.