add a key and value to a map with a key of type int in go

To add a key-value pair to a map in go where the key is of type int, you can do the following:

main.go
myMap := make(map[int]string) // creates an empty map with an int key and string value

key := 42
value := "hello"

myMap[key] = value
135 chars
7 lines

The above snippet declares a map with an integer key and a string value. It then initializes a key-value pair with the integer key of 42 and the string value of "hello". You can access the value of the key by referring to it as myMap[key].

You can also use the insert() function to add a key-value pair to a map. Here's an example:

main.go
myMap := make(map[int]string)

key := 42
value := "hello"

myMap = insert(myMap, key, value)

func insert(m map[int]string, key int, value string) map[int]string {
    m[key] = value
    return m
}
198 chars
12 lines

The insert() function takes a map with an integer key and a string value, a key (also an integer), and a value (a string). It then adds the key-value pair to the map and returns the updated map.

gistlibby LogSnag