Home » Core Golang » How to create, update, delete a map in Golang

How to create, update, delete a map in Golang

A map (or dictionary) is an unordered collection of key-value pairs, where each key is unique. Maps are implemented by hash tables and have efficient add, get and delete operations in Golang. For more information please visit here.

In this article, we’ll learn how to use Golang’s built-in map type.

package main

import "fmt"

func main() {
	var m map[string]int // nil map of string-int pairs

	m1 := make(map[string]int)     // Empty map of string-int pairs
	m2 := make(map[string]int, 50) // Preallocate room for 50 entries

	fmt.Println(len(m))  // prints 0
	fmt.Println(len(m2)) // prints 0

	m1["pi"] = 3 // Add a new key-value pair
	m1["pi"] = 4 // Update value

	if x, found := m1["pi"]; found {
		fmt.Println(x) // Prints "4"
	}

	delete(m1, "pi") // Delete a key-value pair
	fmt.Println(m1)  // Print map: "map[]"

}

akotako

Leave a Reply

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

Back to top