GO Tutorial



MAPS IN GO


Maps in Go

In Go, maps are built-in data structures that store unordered collections of key-value pairs. They provide fast lookups, updates, and deletions based on keys.

Declaring and Initializing Maps

You can declare a map using the map[keyType]valueType syntax. Maps must be initialized before use, typically with make() or a map literal.

var colors map[string]string                // Declared, but nil and unusable yet
colors = make(map[string]string)            // Initialized and ready to use

// Or declare and initialize with values using a map literal
fruits := map[string]string{
    "a": "Apple",
    "b": "Banana",
    "c": "Cherry",
}
  

Adding and Updating Elements

Add or update map entries by assigning a value to a key:

colors := make(map[string]string)
colors["red"] = "#FF0000"       // Add a key-value pair
colors["green"] = "#00FF00"     // Add another
colors["red"] = "#F00"          // Update the value for "red"
  

Accessing Values

Retrieve values by key. If the key doesn’t exist, the zero value for the value type is returned:

colorCode := colors["red"]
fmt.Println(colorCode)          // Output: #F00

unknown := colors["blue"]
fmt.Println(unknown)            // Output: "" (empty string)
  

Checking if a Key Exists

Use the two-value assignment to check if a key exists:

value, exists := colors["blue"]
if exists {
    fmt.Println("Blue color code:", value)
} else {
    fmt.Println("Blue key not found")
}
  

Deleting a Key

Use the built-in delete() function to remove a key-value pair:

delete(colors, "green")    // Removes the "green" key
  

Iterating Over a Map

Use a for range loop to iterate through all key-value pairs:

for key, value := range colors {
    fmt.Printf("Key: %s, Value: %s\n", key, value)
}
  

Important Notes

  • Maps are unordered β€” iteration order is random and can change each time.
  • Maps are reference types, so when assigned or passed to functions, the underlying data is shared.
  • Always initialize a map before use; nil maps cause runtime panic on write.

Summary

Maps in Go offer a flexible and efficient way to manage key-value data. With built-in support for creation, access, update, deletion, and iteration, they are a fundamental data structure you’ll use frequently.


🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review