Sobes.tech
Senior

What is a 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. It stores key-value pairs, where keys are unique, and values can be of any type.

Main features:

  • Keys must be comparable types (e.g., strings, numbers).
  • Values can be of any type.
  • Access to elements via the syntax m[key].
  • You can check for the presence of a key using the second return value: val, ok := m[key].

Example of usage:

package main
import "fmt"

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

    fmt.Println(m["apple"]) // 5

    val, ok := m["orange"]
    if !ok {
        fmt.Println("Key 'orange' not found")
    } else {
        fmt.Println(val)
    }
}