Accessing Elements in a Map
Accessing an element in a map is a very easy task. All you have to do is pass the value of the key using the map name. The value corresponding to that key will be returned.
Syntax:
Value = map_name[key]
Example:
package main
import ("fmt")
func main() {
//creating a map
//map1 maps States and UTs to their capitals
map1:= map[string]string{
"Jammu and Kashmir" : "Srinagar",
"Uttar Pradesh" : "Lucknow",
"Bihar" : "Patna",
"Madhya Pradesh" : "Bhopal",
"Tamil Nadu" : "Chennai",
}
//accessing the value of each key
//i.e. the capital of each State and UT
// map1[key]
fmt.Println("The capital of Uttar Pradesh is : ", map1["Uttar Pradesh"])
fmt.Println("The capital of Madhya Pradesh is : ", map1["Madhya Pradesh"])
fmt.Println("The capital of Bihar is : ", map1["Bihar"])
fmt.Println("The capital of Tamil Nadu is : ", map1["Tamil Nadu"])
fmt.Println("The capital of Jammu and Kashmir is : ", map1["Jammu and Kashmir"])
}
Output:
The capital of Uttar Pradesh is : Lucknow
The capital of Madhya Pradesh is : Bhopal
The capital of Bihar is : Patna
The capital of Tamil Nadu is : Chennai
The capital of Jammu and Kashmir is : Srinagar
Updating and Adding Elements in a Map
Both updating and adding elements in a map can be accomplished by using the variable name of the map, followed by the key value in square brackets [], and the equal (=)operator to set a new value.
Syntax:
Map_name[key] = value
Example 1: adding a new element in a map
package main
import ("fmt")
func main() {
//creating a map
//map1 maps States and UTs to their capitals
map1:= map[int]string{
1 : "One",
2 : "Two",
3 : "Three",
4 : "Four",
5 : "Five",
}
// adding a new element in the map "map1"
map1[6] = "Six"
// check the elements of the map1
// to assert that 6: Six has been added
fmt.Println(map1)
}
Output:
map[1:One 2:Two 3:Three 4:Four 5:Five 6:Six]
Example 2: updating an element in a map
package main
import ("fmt")
func main() {
//creating a map
//map1 maps digits to their spellings
map1:= map[int]string{
1 : "One",
2 : "Two",
3 : "Three",
4 : "Four",
5 : "Five",
}
//updating 4: Four to 4: Eight
map1[4] = "Eight"
// check the elements of the map1
// to assert that 4: Four has been updated to 4: Eight
fmt.Println(map1)
}
Output:
map[1:One 2:Two 3:Three 4:Eight 5:Five]
Remove an Element From a Map
The delete() function is used to delete an element from the map.
Syntax:
delete(map_name, key)
Example:
package main
import ("fmt")
func main() {
//creating a map
//map1 maps numbers to their spellings
map1:= map[int]string{
1 : "One",
2 : "Two",
3 : "Three",
4 : "Four",
5 : "Five",
}
// deleting 2: Two
delete(map1, 2)
//map after the key 2 is deleted
fmt.Println(map1)
}
Output:
map[1:One 3:Three 4:Four 5:Five]
Check for a specific element in a map
When the requested key is not present, maps in Go will return a zero value for the map's value type.
Now suppose that a particular key is not at all present in the map. Trying to fetch the value of that key would give zero as the output. It gives a sense that the value of the key is zero, whereas it may be possible that zero is displayed because the key is not present in the map.
Example:
package main
import ("fmt")
func main() {
map1:= map[string]int{
"one" : 1,
"two" : 2,
"three" : 3,
}
// although the key four is not present
// yet the output is 0
// which is not correct
fmt.Println(map1["four"])
}
Output:
0
In order to solve this problem, Go also returns a second boolean value. The second boolean value is true if the key is present in the map and it is false if the key is not present in the map.
Example:
package main
import ("fmt")
func main() {
map1:= map[string]int{
"one" : 1,
"two" : 2,
"three" : 3,
}
// correct way to check existence of an element
// check for the existence of "four"
value, isKeyPresent :=map1["four"]
fmt.Println(value, isKeyPresent) // returns 0 false
//check for the existence of two
value1, isTwoPresent := map1["two"]
fmt.Println(value1, isTwoPresent) //returns 2 true
}
Output:
0 false
2 true
Iterating Over Maps
We can iterate over the map using the range keyword. It is used to iterate over a variety of data structures.
Example:
package main
import ("fmt")
func main() {
// declare and add key-value pairs to the map
map1:= map[string]int{
"one" : 1,
"two" : 2,
"three" : 3,
"four" : 4,
"five" : 5,
}
// use the range keyword to iterate over the map
// Each iteration returns key and value
for key, value := range map1{
fmt.Println(key, value)
}
}
Output:
one 1
two 2
three 3
four 4
five 5
Maps are Reference Types
Internally maps maintain a hash table in order to efficiently store the key-value pair data. In case two map variables refer to the same hash table, changing the content of one variable affects the content of the other.
Example:
package main
import ("fmt")
func main() {
// declare and add key-value pairs to the map
map1:= map[string]string{
"India" : "New Delhi",
"United Kingdom" : "London",
"Germany" : "Berlin",
"Japan" : "Tokyo",
"Netherlands" : "Amsterdam",
}
// map2 refers to the hash table of map1
map2 := map1
// map2 contains everything that map1 contained
fmt.Println("Map2 contents are : \n",map2)
// change the value for Germany using map2
map2["Germany"] = "London"
// change is reflected for map1 also
fmt.Println("Map1 contents are : \n",map1)
}
Output:
Map2 contents are
map[Germany:Berlin India:New Delhi Japan:Tokyo Netherlands:Amsterdam United Kingdom:London]
Map1 contents are
map[Germany:London India:New Delhi Japan:Tokyo Netherlands:Amsterdam United Kingdom:London]
Explanation
It can be seen that when the value for Germany is changed from Berlin to London using map2, the change is also reflected for map1. Therefore we can say that the maps are reference types.
Need For Maps
Maps can be helpful in situations like:
- It maps keys to values, resulting in key-value pairs that are a useful way to store data.
- Since the keys in the map are unique, searching for a particular key is very fast and one of the vital reasons why we use maps.
- Using maps in Go is very easy and simple.
FAQs
-
How do you create an empty map in Go?
To make an empty map in Go, we follow the below syntax:
make(map[key-type]val-type).
-
How do you access an element in a map in Golang?
We can simply pass the value of the key using the map name to access an element in a map in Golang.
-
What do you mean by an unordered map in Golang?
The maps in Golang are unordered, meaning they do not compulsorily maintain the order in which the key-value pairs are added in the map.
-
What is the use of the range keyword in maps in Go?
We can iterate over the map using the range keyword.
-
How can you remove an element from a map in Go?
The delete() function is used to delete an element from the map.
Key Takeaways
In this article, we have extensively discussed maps in Go and the various operations involved in the maps.
- A map in Go is an unordered collection of key-value pairs. It maps keys to values. The keys are unique within a map, while the values may not be.
- We can initialize a map using the built-in make() function. We just need to pass the type of the map to the make() function.
- We can simply pass the value of the key using the map name to access an element in a map in Golang.
- We can iterate over the map using the range keyword.
We hope that this blog has helped you enhance your knowledge regarding maps in Go and if you would like to learn more, check out our articles here. Do upvote our blog to help other ninjas grow. Happy Coding!