Sobes.tech
Junior — Middle

È possibile usare strutture come chiavi in un array associativo o mappa?

sobes.tech AI

Risposta dell'AI

In Go, le chiavi in una mappa possono essere solo di tipi che supportano l'operazione di confronto (l'operatore ==). Le strutture possono essere usate come chiavi se tutti i loro campi sono confrontabili. Ad esempio, se una struttura contiene solo tipi di base (int, string, ecc.), può essere usata come chiave. Tuttavia, se la struttura contiene slice, mappe o funzioni, non può essere usata come chiave.

Esempio:

package main

import "fmt"

type Point struct {
    X, Y int
}

func main() {
    m := make(map[Point]string)
    p := Point{X: 1, Y: 2}
    m[p] = "punto"
    fmt.Println(m[p]) // output: punto
}

Se la struttura contiene campi non confrontabili, il compilatore genererà un errore.