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 package
import(
"fmt"
)
//program execution starts here
func main(){
//Create a new map using make
students := make(map[string]int)
//Add first pair
students["john"] = 10
//display map after adding first pair
fmt.Println("After adding one student", students)
//Add second pair
students["steve"] = 15
//display the map after adding second pair
fmt.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 type string and the value is of the type int.

  • 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.

Free Resources