Maps

A Map is some kind of more flexible array. With an array, you have to have an integer as the key like this:

names[1] = "hugo"

So this array have an int type as index and a string as the element type.

With a map you are free to define not only the element type, but also the index type. Maps are created with make.

So this creates a map with a string index type and a float element type:

package main
import "fmt"

func main() {
    weights := make (map[string]float64)
    weights["conan"] = 116.5
	fmt.Println(weights["conan"])
}

Looping

package main

package main

import "fmt"

func main() {
  heroes := map[string]bool{
		"peter": true,
		"gwen":  false,
		"bruce": true}
	for i := range heroes {
		fmt.Println(i)
	}
	for i, supe := range heroes {
		fmt.Println(i, supe)
	}
}

With go run maps.go we get:

peter
gwen
bruce
peter true
gwen false
bruce true

Define a pre-filled map

heroes := map[string]bool{
		"peter": true,
		"gwen":  false,
		"bruce": true}
Code  Meaning
:=  create variable and infer type
[] map
string  of type string
{} with this content

Range through map

With

 11     for i, supe := range heroes {

You get the index as integer number in i and the element in supe. If you just want the supes, you may do:

 11     for _, supe := range heroes {
 12         fmt.Println( supe)
 13     }

The _ underscore operator is like a bin.

Later we will use maps with string index type and interface element type for all these json files.

But first to creating your own datatypes with structs.

See also

Source

See the full source on github.

Sources