create a map with a key of type int in go

To create a map in Go with key of type int, we can use the make function along with the map keyword. Here is an example code snippet:

main.go
myMap := make(map[int]string)
30 chars
2 lines

This code defines a new empty map myMap with keys of type int and values of type string. We can then add new key-value pairs to the map using the bracket notation:

main.go
myMap[1] = "Hello"
myMap[2] = "World"
38 chars
3 lines

We can also retrieve values from the map using the same bracket notation:

main.go
fmt.Println(myMap[1]) // output: Hello
39 chars
2 lines

Be sure to handle the case where the key does not exist in the map, as attempting to retrieve a non-existent key will result in a runtime error in Go. One way to check if a key exists in a map is to use the "comma ok" syntax:

main.go
value, exists := myMap[3]
if exists {
    fmt.Println(value)
} else {
    fmt.Println("Key not found")
}
105 chars
7 lines

related categories

gistlibby LogSnag