Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Go Lang - Maps

Understanding Maps in Go

Maps in Go are unordered collections of key-value pairs.

Key Points:

  • Maps are used to store key-value pairs where each key is unique.
  • Maps are reference types in Go.
  • Elements in a map are accessed using their keys.

Example of Maps in Go

Below is an example demonstrating the use of maps in Go:


// Example: Working with maps in Go
package main

import (
    "fmt"
)

func main() {
    // Declare and initialize a map
    employees := map[string]int{
        "John":   35,
        "Jane":   29,
        "Doe":    40,
    }

    // Access elements of the map
    fmt.Println("Age of John:", employees["John"])

    // Add a new key-value pair to the map
    employees["Alice"] = 32

    // Iterate over the map
    fmt.Println("Employees:")
    for name, age := range employees {
        fmt.Println(name, "-", age)
    }
}
          

Manipulating Maps in Go

Maps in Go support various operations like adding, updating, deleting, and iterating over key-value pairs.


// Example: Manipulating maps in Go
package main

import (
    "fmt"
)

func main() {
    // Declare and initialize a map
    languages := map[string]string{
        "en": "English",
        "fr": "French",
        "es": "Spanish",
    }

    // Update a value in the map
    languages["fr"] = "Français"

    // Delete a key from the map
    delete(languages, "es")

    // Check if a key exists in the map
    if lang, ok := languages["en"]; ok {
        fmt.Println("Value for 'en':", lang)
    } else {
        fmt.Println("'en' not found")
    }

    // Iterate over the map
    fmt.Println("Languages:")
    for code, name := range languages {
        fmt.Println(code, "-", name)
    }
}
          

Summary

This guide provided an overview of understanding and using maps in Go, including examples of declaring maps, accessing map elements, manipulating maps by adding, updating, deleting keys, and iterating over map elements. By using maps effectively, you can manage key-value data pairs efficiently in Go.