Golang in sixty seconds — tricks with maps

Map of Edinburgh
Not this kind of map… (1834 Edinburgh by William Barnard Clarke)

In a previous article I mentioned the strings.Count function. Here's an alternative for more complex use cases.

Lets say we have a slice or array of people:

type Person struct {
 name string
 age  int
}
people := []Person{{name: "Bob", age: 21}, {name: "Sam", age: 28}, {name: "Ann", age: 21}, {name: "Joe", age: 22}, {name: "Ben", age: 28}}

If we want to understand the frequency of ages of our people, we can make use of a map :

ageDistribution := map[int]int
for _, person := range people {
  ageDistribution[person.age]++
}
fmt.Println(ageDistribution) // map[21:2 22:1 28:2]

All we're doing here is looping over each person in our slice and incrementing the value that we have stored for that age, essentially counting them. You can try it here

Knowing the distribution of ages may not be all that useful, but you may want to be able to quickly get all the people of a certain age, in which case you could do this:

peopleByAge := make(map[int][]Person)
for _, person := range people {
  peopleByAge[person.age] = append(peopleByAge[person.age], person)
}
fmt.Println(peopleByAge[21]) // [{Bob 21} {Ann 21}]

You can try it here

Richard Bell

Self taught software developer with 12 years experience excelling at JavaScript/Typescript, React, Node and AWS.

I love learning and teaching and have mentored several junior developers over my career. I find teaching is one of the best ways to solidify your own learning, so in the past few years I've been maintaining a technical blog where I write about some things that I've been learning.

I'm passionate about building a teams culture and processes to make it efficient and satisfying to work in. In many roles I have improved the quality and reliability of the code base by introducing or improving the continuous integration pipeline to include quality gates.