Map in golang

Map in golang

Map is a data structure which contains key value pair. In Golang make function returns a map of the given type, initialized and ready for use. In this article, we will be creating a map using make function and will perform operation on map like add, delete and iterate.

package main

import "fmt"

func main() {
	//create a map
	m := make(map[string]int)

	// assign value
	m["key1"] = 12
	m["key2"] = 20

	fmt.Println(m)

	// get value from map
	value1 := m["key1"]
	fmt.Printf("key1 : %d", value1)

	// get length of map
	fmt.Printf("\nLength : %d", len(m))

	// get all key and value from map
	for key, value := range m {
		fmt.Printf("\n%s : %d", key, value)
	}

	// delete key from map
	delete(m, "key1")
	fmt.Println("\ncontent of map after deletion of 'key1'")
	for key, value := range m {
		fmt.Printf("%s : %d", key, value)
	}
}

Output

map[key1:12 key2:20]
key1 : 12
Length : 2
key1 : 12
key2 : 20
content of map after deletion of 'key1'
key2 : 20

Stay tuned for more updates and tutorials !!!

Leave a Reply

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