Instagram
youtube
Facebook
Twitter

Maps in Golang

A map is a built-in data structure in Golang that stores a collection of key-value pairs. Each key in a map is unique, and the keys are used to retrieve corresponding values. Maps are similar to dictionaries in language like Python. They are widely used for efficient data retrieval and storage.

Creating a Map

To create a map in Go, we use the make function or the map function. Here's how we can create an empty map and initialize it using map:

// Using make
studentAge := make(map[string]int)

// Using map
studentGrades := map[string]int{
    "maths": 92,
    "english":   85,
    "hindi": 78,
}


Adding and Accessing Elements

We can add and access elements in a map using the square brackets.

Example:

package main

import "fmt"

func main() {
    // Creating an empty map using the make function
    studentAge := make(map[string]int)

    // Adding elements to the map
    studentAge["Allen"] = 20
    studentAge["jack"] = 22

    // Accessing elements from the map
    age := studentAge["Allen"]
    fmt.Println("Allen's age:", age)
}

Output:

Allen's age: 20

Checking if a Key Exists

We can check if a key exists in a map using a combination of the value and a boolean:

Example:

package main

import "fmt"

func main() {
    // Creating an empty map using the make function
    studentAge := make(map[string]int)

    // Adding elements to the map
    studentAge["Allen"] = 20
    studentAge["jack"] = 22

    // Checking if a key exists in the map
    Age, exists := studentAge["Charlie"]
    if exists {
        fmt.Println("Charlie's age:", Age)
    } else {
        fmt.Println("Charlie not found")
    }
}

 Output:

Charlie not found

Deleting Elements

We can delete elements from a map using the delete function:

package main

import "fmt"

func main() {
    // Creating an empty map using the make function
    studentAge := make(map[string]int)

    // Adding elements to the map
    studentAge["Allen"] = 20
    studentAge["jack"] = 22
    
    // Deleting element
    delete(studentAge, "jack")

    // Checking if a key exists in the map
    Age, exists := studentAge["jack"]
    if exists {
        fmt.Println("jack's age:", Age)
    } else {
        fmt.Println("jack not found")
    }
}

 Output:

jack not found