Contents

Go Tutorial Part 12 - Map

  1. Maps are key value pairsSection 5: Maps
  2. Keys and values are of statically typed(All keys of same types and all values of same type)

1 Declare a map

1.1

package main

import "fmt"

func main() {
	colors := map[string]string{
		"red":    "#578",
		"greeen": "#579",
	}
	fmt.Println(colors)
}

1.2

package main

import "fmt"

func main() {
    var colors map[string]string
}

1.3

package main

import "fmt"

func main() {
    colors := make(map[string]string)
    colors["white"] = "#555555"
    delete(colors["white"])
}

2 Iterating over maps


package main

import "fmt"

func main() {
	colors := map[string]string{
		"red":    "#578",
		"greeen": "#579",
	}
	printMap(colors)
}

func printMap(c map[string]string) {
	for color, hex := range c {
		fmt.Println("Hex code for ", color, " is ", hex)
	}
}

Hex code for  red  is  #578
Hex code for  greeen  is  #579

3 Struct vs Map

3.1 Struct

  1. Values can be of different type
  2. keys do not support indexing
  3. Value Type!
  4. You need to know all the different fields at compile time
  5. Use to represent a “thing” with a lot of different properties

3.2 Map

  1. All keys must be of same type
  2. All values must be of same type
  3. keys are indexed we can iterate over them
  4. Used to represent a collection of related properties
  5. Do not need to know all the keys at compile time
  6. Reference Type!