Maps

An unordered collection of key:value pairs. We can access value from a map using key and its very quick.

A map is implemented using hash table.

Declaration and initialization of a map Run Code

package main

import (
	"fmt"
)

func main() {

	// Create a nil map (declaration without initialization)
	var student map[string]int
	fmt.Println(student) // map[]

	// Create a map using in-built make method
	months := make(map[string]int)
	fmt.Println(months) // map[]

	// Create a map using map literal
	months = map[string]int{}
	fmt.Println(months) // map[]
}

some operations on map Run Code

package main

import (
	"fmt"
)

func main() {
	// Create an empty map
	months := map[string]int{}

	// Add elements to map
	months["Jan"] = 1
	months["Feb"] = 2
	months["Mar"] = 3
	months["Apr"] = 4
	months["May"] = 5
	months["Jun"] = 6
	months["Jul"] = 7
	months["Aug"] = 8
	months["Sep"] = 9
	months["Oct"] = 10
	months["Nov"] = 11
	months["Dec"] = 12

	// Get elements from map
	secondMonth := months["Feb"]
	fmt.Println(secondMonth) // 2

	// Get value from map and check its existance
	thridMonth, ok := months["ABCD"]
	fmt.Println(thridMonth, ok) // 0 false

	// Print length of map
	fmt.Println("length =", len(months)) // length = 12

	// Remove an element from map
	delete(months, "Jan")

	// Print length of map
	fmt.Println("length =", len(months)) // length = 11

	// Iterate over map
	for key, value := range months {
		fmt.Printf("key: %s, value: %d\n", key, value)
	}

}

Output:
2
0 false
length = 12
length = 11
key: May, value: 5
key: Jul, value: 7
key: Sep, value: 9
key: Feb, value: 2
key: Mar, value: 3
key: Oct, value: 10
key: Nov, value: 11
key: Dec, value: 12
key: Apr, value: 4
key: Jun, value: 6
key: Aug, value: 8

Leave a Reply

Your email address will not be published. Required fields are marked *