How to create a map with non-string keys in Go?

In Go, we can create a map with non-string keys using custom types as keys in the map. Here's an example:

package main import "fmt" type City struct { Name string State string } func main() { // Create a map with City as key and population as value population := make(map[City]int) // Create some cities city1 := City{Name: "New York", State: "NY"} city2 := City{Name: "San Francisco", State: "CA"} // Add city population to the map population[city1] = 8623000 population[city2] = 883305 // Access the population using city keys fmt.Println("Population of New York:", population[city1]) fmt.Println("Population of San Francisco:", population[city2]) }

In this example, we have defined a City struct with Name and State fields. We then create a map population with City as the key type and int as the value type.

We create two City objects, city1 and city2, and use them as keys to store their respective populations in the population map.

To access the population, we use the city keys just like we would with a string key.

Output:

Population of New York: 8623000 Population of San Francisco: 883305