Map in Golang Part-I

Rajat Yadav
1 min readMar 20, 2021

In Go map is a keyword to create a map with keys and values of certain type.

Map is a unordered collection of key-value pairs, where each key is unique.

Lets create a map, a map can be created by two ways:

  1. Declaring a variable of type map.
  2. Using make keyword.
var m1 map[string]int
m2 := make(map[string]int)

We can also provide length to a map, below example map m3 has size 100.

m3 := make(map[string]int, 100)
fmt.Println(len(m3)) // 100

Lets add key-value to our map.

m4 := make(map[string]float64)
m4["pi"] = 3.16
m4["e"] = 2.71
fmt.Println(m4) // "map[e:2.71828 pi:3.1416]"

Lets get a key-value from map.

value, isKeyExists := m4["pi"]
fmt.Println(value, isKeyExists) // 3.14 true
value, isKeyExists := m4["pie"]
fmt.Println(value, isKeyExists) // 0 false

Lets delete a key-value from map.

delete(m4, "pi")
fmt.Println(m4) // "map[e:2.71828]"

Iteration over map.

for key, value := range m4 {
fmt.Println(key, value)
}
// pi 3.16
// e 2.71

Next what?

Golang maps in Goroutine…

Thank you !!! .. Feedback will be highly appreciated.

--

--