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.go30 chars2 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.go38 chars3 lines
We can also retrieve values from the map using the same bracket notation:
main.go39 chars2 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.go105 chars7 lines
gistlibby LogSnag