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 := []string{"peter", "gwen", "bruce"}
 
    for i := range heroes {
        fmt.Println(i)
    }
    for i, supe := range heroes {
        fmt.Println(i, supe)
    }
}
  1 package main
  2
  3 import "fmt"
  4
  5 func main() {
  6     heroes := []string{"peter", "gwen", "bruce"}
  7
  8     for i := range heroes {
  9         fmt.Println(i)
 10     }
 11     for i, supe := range heroes {
 12         fmt.Println(i, supe)
 13     }
 14 }

With go run maps.go we get:

0
1
2
0 peter
1 gwen
2 bruce

Define a pre-filled map

  6     heroes := []string{"peter", "gwen", "bruce"}
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