In Go a map is ideal for fast lookups—we can find, add and remove elements with great speed. But it is not good for iterating (looping) over elements.
We sometimes want a slice of keys, values, or pairs. And a "flat slice" one where all the keys and values are stored together one after another is also helpful.
Here we begin with a map of string
keys and string
values. We then show how to get just the keys, or just the values, in a separate string
slice.
append()
.package main import "fmt" func main() { // Create example map. m := map[string]string{ "java": "coffee", "go": "verb", "ruby": "gemstone", } // Convert map to slice of keys. keys := []string{} for key, _ := range m { keys = append(keys, key) } // Convert map to slice of values. values := []string{} for _, value := range m { values = append(values, value) } // Print the results. fmt.Println("MAP ", m) fmt.Println("KEYS SLICE ", keys) fmt.Println("VALUES SLICE", values) }MAP map[go:verb java:coffee ruby:gemstone] KEYS SLICE [java go ruby] VALUES SLICE [coffee verb gemstone]
Sometimes in Go programs we want a slice of 2-element string
arrays from our map. We can create these in a slice of pairs.
package main import "fmt" func main() { m := map[string]string{ "java": "coffee", "go": "verb", "ruby": "gemstone", } // Convert map to slice of key-value pairs. pairs := [][]string{} for key, value := range m { pairs = append(pairs, []string{key, value}) } // Convert map to flattened slice of keys and values. flat := []string{} for key, value := range m { flat = append(flat, key) flat = append(flat, value) } // Results. fmt.Println("MAP ", m) fmt.Println("PAIRS SLICE ", pairs) fmt.Println("FLAT SLICE ", flat) }MAP map[go:verb java:coffee ruby:gemstone] PAIRS SLICE [[java coffee] [go verb] [ruby gemstone]] FLAT SLICE [java coffee go verb ruby gemstone]
We can extract data from a map by using for-range
loops. When a map is iterated over in this kind of loop, we access each key and value.
Often constructs like slices that are "flattened" contain all keys and values together are useful in real programs. They may also be simpler to use.