Open In App

Golang Maps

Last Updated : 29 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In Go (Golang), a map is a powerful and versatile data structure that acts as a collection of unordered key-value pairs. Maps are widely used due to their efficiency in providing fast lookups, updates, and deletions based on keys.

What is a Map?

A map in Go is essentially a reference to a hash table. This reference type is inexpensive to pass—taking up only 8 bytes on a 64-bit machine and 4 bytes on a 32-bit machine.

  • Keys must be unique and of a comparable type, such as int, float64, rune, string, arrays, structs, or pointers. However, types like slices and non-comparable arrays or structs cannot be used as keys.
  • Values, on the other hand, can be of any type, including another map, pointers, or even reference types.

Example

package main
import "fmt"

func main() {
// Creating and initializing a map with names and ages
ages := map[string]int{
"A": 30,
"B": 25,
"C": 35,
}

// Retrieving and printing B's age
fmt.Println("B's age:", ages["B"])
}

Syntax

map[Key_Type]Value_Type{}                                              # Simple Initialization

make(map[Key_Type]Value_Type, initial_Capacity) # Using the make() Function
make(map[Key_Type]Value_Type)

Maps Initialization

Maps must be initialized before use. There are two main methods for creating and initializing maps in Go:

Simple Initialization

You can create a map without using the make() function by using the following syntax:

Syntax

# An empty map
map[Key_Type]Value_Type{}

# Map with key-value pairs
map[Key_Type]Value_Type{key1: value1, ..., keyN: valueN}

Example:

Go
package main
import "fmt"

func main() {
    // Creating and initializing a map with names and ages
    ages := map[string]int{
        "A": 30,
        "B": 25,
        "C": 35,
    }

    // Retrieving and printing B's age
    fmt.Println("B's age:", ages["B"])
}

Output
B's age: 25

Using the make() Function

Another way to create a map is by using the built-in make() function.

Syntax

make(map[Key_Type]Value_Type, initial_Capacity)
make(map[Key_Type]Value_Type)

Example:

Go
package main
import "fmt"

func main() {
    // Creating a map using the make function
    ages := make(map[string]int)

    // Initializing the map with names and ages
    ages["A"] = 30
    ages["B"] = 25
    ages["C"] = 35

    // Retrieving and printing B's age
    fmt.Println("B's age:", ages["B"])
}

Output
B's age: 25

Important Operations with Maps

Iterating Over a Map

You can iterate through a map using the for range loop. Since maps are unordered, the order of iteration may vary.

Example:

for key, value := range myMap {
fmt.Println(key, value)
}

Adding Key-Value Pairs

You can add key-value pairs to an initialized map using the following syntax:

Syntax

myMap[key] = value

If the key already exists, its value will be overwritten.

Example:

myMap[3] = "Three" // Adds a new entry
myMap[1] = "Updated One" // Updates existing entry

Retrieving Values

You can retrieve a value from a map using its key:

value := myMap[key]

If the key does not exist, it will return the zero value for the map’s value type.

Checking Key Existence

To check if a key exists in a map, you can use the following syntax:

Syntax

value, exists := myMap[key]

If exists is true, the key is present; if false, it is not.

Example:

if pet, ok := myMap[2]; ok {
fmt.Println("Key exists:", pet)
} else {
fmt.Println("Key does not exist")
}

Deleting a Key

You can delete a key from a map using the built-in delete() function:

Syntax

delete(myMap, key)

Example:

delete(myMap, 1) // Removes the key 1 from the map

Modifying Maps

Since maps are reference types, assigning one map to another variable will not create a copy but will instead reference the same underlying data structure. Thus, modifications to one map will affect the other.



Next Article
Article Tags :

Similar Reads

three90RightbarBannerImg
  翻译: