To create a map with a custom data type as a key in Go, you need to ensure that the key type is comparable. Go maps require keys to be comparable to determine if two keys are equal or not. Custom types can be used as keys as long as they implement the equality operator (==
) and the hash()
method.
Here is an example of creating a map with a custom data type as a key in Go:
package main
import (
"fmt"
)
type Coordinate struct {
latitude float64
longitude float64
}
func main() {
// Create a map with Coordinate as key and string as value
myMap := make(map[Coordinate]string)
// Add data to the map
myMap[Coordinate{40.7128, -74.0060}] = "New York"
myMap[Coordinate{34.0522, -118.2437}] = "Los Angeles"
// Access data from the map
fmt.Println(myMap[Coordinate{40.7128, -74.0060}]) // Output: New York
fmt.Println(myMap[Coordinate{34.0522, -118.2437}]) // Output: Los Angeles
}
In this example, we define the Coordinate
struct with latitude
and longitude
fields. We create a map called myMap
with Coordinate
as the key type and string
as the value type. We add elements to the map using Coordinate
keys, and then retrieve the corresponding values by providing a Coordinate
key.