In this article, we will see how to access a map using its reference in golang.

What is map?

A map is a collection of key-value pairs, where each key is unique, and its corresponding value can be accessed using the key.

Let’s first see how to create a map in golang

package main

import "fmt"

func main() {
    // Creating a map
    myMap := make(map[string]int)

    // Adding data to the map
    myMap["John"] = 25
    myMap["Jane"] = 30
    myMap["Bob"] = 40

    // Accessing data from the map
    fmt.Println("John's age is", myMap["John"])
}

In the above code, we created a map named “myMap” and populated it with three key-value pairs and then accessed the value associated with the key “John” using the syntax “myMap[“John”]” and printed it to the console.

Now, let us see how to access a map using its reference.

In Golang, maps are reference types, which means that when you pass a map to a function or assign it to a variable, you are actually passing a reference to the original map.

Following is an example:

package main

import "fmt"

func main() {
    // Creating a map
    myMap := make(map[string]int)

    // Adding data to the map
    myMap["John"] = 25
    myMap["Jane"] = 30
    myMap["Bob"] = 40

    // Assigning the map reference to a variable
    myMapRef := &myMap

    // Accessing data from the map using the reference
    fmt.Println("John's age is", (*myMapRef)["John"])
}

In the above example, we created a map called “myMap” and populated it with data and then assigned the reference to “myMap” to a variable named “myMapRef“. To access the data from the map using the reference, we used the syntax “(*myMapRef)[“John”]”, which is equivalent to “myMap[“John”]”.

Categorized in:

Tagged in: