Go Tutorial Part 12 - Map
Contents
- Maps are key value pairsSection 5: Maps
- 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
- Values can be of different type
- keys do not support indexing
- Value Type!
- You need to know all the different fields at compile time
- Use to represent a “thing” with a lot of different properties
3.2 Map
- All keys must be of same type
- All values must be of same type
- keys are indexed we can iterate over them
- Used to represent a collection of related properties
- Do not need to know all the keys at compile time
- Reference Type!