Sobes.tech
Senior

What can you tell about map in Go?

sobes.tech AI

Answer from AI

In Go, a map is a built-in data type that implements an associative array or dictionary, where keys are mapped to values.

Features of maps in Go:

  • Keys and values have specific types, for example, map[string]int — keys are strings, values are integers.
  • Maps are initialized using the make function, for example: m := make(map[string]int).
  • Access elements via m[key].
  • If the key is absent, the zero value of the value type is returned.
  • You can check for the presence of a key using the second return value: val, ok := m[key].
  • Maps are unordered; iteration order is random.
  • Maps are not safe for concurrent use; synchronization is needed for concurrent access.

Example:

package main
import "fmt"

func main() {
    m := make(map[string]int)
    m["apple"] = 5
    m["banana"] = 3

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

    // Delete a key
    delete(m, "banana")
}