What is add to map in Golang?
Map is an unordered collection of key-value pairs, where the keys are unique.
In this shot, we will learn how to add key and value pairs to the map.
Syntax
If we have the following map:
map_name:= make(map[key_type]value_type)
We’ll use the following syntax to add a key and value pair:
map_name["key"] = value
In the syntax above, map_name is the name of the map variable. The new pair,key and value, is being added to the map.
Example
In the code example below, we are creating a map that contains students’ names as keys and their ages as the values.
We will add students one by one to the map.
package main//import fmt packageimport("fmt")//program execution starts herefunc main(){//Create a new map using makestudents := make(map[string]int)//Add first pairstudents["john"] = 10//display map after adding first pairfmt.Println("After adding one student", students)//Add second pairstudents["steve"] = 15//display the map after adding second pairfmt.Println("After adding two students", students)}
Code explanation
In the code snippet above:
-
Line 5: We import the package
fmt, which is used for printing statements. -
Line 9: The program execution starts from the function
main(). -
Line 12: We declare a new map using the function
make, where the key is of the typestringand the value is of the typeint. -
Line 15: We add the first student,
john, to the map and assign his age as the value. -
Line 18: We display the map after adding the first student.
-
Line 21: We add the second student,
steve, to the map and assign his age as the value. -
Line 24: We display the map after adding the second student.