Mapping in Golang




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

The next tutorial:





  • Introduction to the Go Programming Language
  • Go Language Syntax
  • Go Language Types
  • Pointers in Go Programming
  • Simple Web App in Go Programming
  • Structs in the Go Programming Language
  • Methods in Go Programming
  • Pointer Receivers in Go Programming
  • More Web Dev in Go Language
  • Acessing the Internet in Go
  • Parsing XML with Go Programming
  • Looping in Go Programming
  • Continuing our Go Web application
  • Mapping in Golang
  • Mapping Golang sitemap data
  • Golang Web App HTML Templating
  • Applying templating to our Golang web app
  • Goroutines - Concurrency in Goprogramming
  • Synchronizing Goroutines - Concurrency in Golang
  • Defer - Golang
  • Panic and Recover in Go Programming
  • Go Channels - Concurrency in Go
  • Go Channels buffering, iteration, and synchronization
  • Adding Concurrency to speed up our Golang Web Application