BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: Maps

Go 1.23

Maps are Go's built-in associative data type (hashes or dicts). This example covers creating maps, adding/deleting keys, checking for existence, and the random iteration order.

Code

package main

import "fmt"

func main() {
    // 1. Creating a Map
    // make(map[KeyType]ValueType)
    m := make(map[string]int)

    // 2. Setting Key-Values
    m["k1"] = 7
    m["k2"] = 13
    fmt.Println("Map:", m)

    // 3. Getting Values
    v1 := m["k1"]
    fmt.Println("v1:", v1)

    // 4. Getting Non-Existent Keys
    // Returns the zero value of the value type (0 for int).
    v3 := m["k3"]
    fmt.Println("v3 (non-existent):", v3)

    // 5. Checking Existence (Comma ok idiom)
    // val, ok := map[key]
    _, ok := m["k3"]
    fmt.Println("k3 exists?", ok)

    if val, ok := m["k2"]; ok {
        fmt.Println("k2 value:", val)
    }

    // 6. Deleting Keys
    delete(m, "k2")
    fmt.Println("Map after delete:", m)

    // 7. Map Literal
    n := map[string]int{"foo": 1, "bar": 2}
    fmt.Println("Literal:", n)
}

Explanation

Go maps are a robust, built-in implementation of hash tables, designed to provide highly efficient, constant-time complexity operations for inserting, retrieving, and deleting key-value pairs. As a reference type, a map variable essentially functions as a pointer to a complex runtime header structure, meaning that passing a map to a function allows for the direct modification of the underlying data without incurring the cost of copying the entire dataset. It is imperative to note that map iteration order in Go is deliberately randomized by the runtime to preclude developers from relying on implementation details, thereby enforcing robust coding practices that do not depend on deterministic ordering.

The "comma ok" idiom represents a critical pattern for safe map access, allowing developers to distinguish unambiguously between a key that is genuinely missing and one that simply contains the type's zero value. Furthermore, while maps are powerful, they are not inherently safe for concurrent access; in multi-threaded environments involving concurrent writes, developers must utilize synchronization primitives like sync.Mutex or the specialized sync.Map to prevent race conditions and ensure data integrity.

  • Reference Type: Passing a map to a function passes a reference; changes are visible to the caller.
  • Unordered: Iteration order is randomized.
  • Concurrency: Maps are not safe for concurrent use. Use sync.Map or a mutex for that.
  • Zero Value: A nil map behaves like an empty map for reading, but writing to it causes a panic. Always use make or a literal.

Code Breakdown

8
Initializing a map using 'make'. The syntax is 'map[KeyType]ValueType'. Here, keys are strings and values are integers.
21-22
Accessing a missing key. 'k3' is not in the map, so Go returns the zero value for an int, which is 0. It does NOT throw an error.
26
The "comma ok" idiom. This is the correct way to check if a key exists. 'ok' will be true if 'k3' is present, and false otherwise. The underscore '_' ignores the actual value.
34
Deleting a key. The built-in 'delete' function removes the key-value pair. If the key doesn't exist, it does nothing (no error).