Welcome to part 14 of the Go programming tutorial series, where we're going to cover maps
. In the previous tutorial, we've been working on parsing XML sitemaps for data on articles. In our case, we've got titles, keywords, and URLs that link to the articles. We'd like to be able to store these into maps like: Title: [keywords, url]
.
A map in go starts off like: map[KeyType]ValueType
. Let's say you wanted to have a map of student names and their grades. To begin, you'd setup your variable:
var grades map[string]float32
In Go, maps are reference types, and they point to anything with value. You cannot write to grades
above, because it points nowhere at the moment. So, we can intitialize it with make
, so it will look more like:
grades := make(map[string]float32)
Awesome, now let's populate this grades
map with some data:
grades["Timmy"] = 42 grades["Jess"] = 92 grades["Sam"] = 71
Now, we could output this map:
fmt.Println(grades)
map[Timmy:42 Jess:92 Sam:67]
We can also select for specific values:
tims_grade := grades["Timmy"] fmt.Println(tims_grade)
42
We can remove items from the map by key, like so:
delete(grades,"Timmy") fmt.Println(grades)
map[Jess:92 Sam:71]
We can finally iterate over maps with range
like we've seen before. This time, range produces key and value:
for k, v := range grades { fmt.Println(k,":",v) }
Jess : 92 Sam : 71