To add a key-value pair to a map in Go, you can simply use the following syntax:
main.go49 chars3 lines
In this example, a map called myMap
is created using the make()
function, which initializes an empty map. Then, a key-value pair is added to myMap
using the square bracket notation ([]
) and the equal sign (=
). The key is of type string
, and the value is of type int
.
Alternatively, you can also use the map
literal syntax to initialize and add key-value pairs to a map in one line:
main.go62 chars2 lines
In this example, myMap
is initialized with three key-value pairs: "apple":2, "orange":3, and "banana":1. Notice that the key-value pairs are specified using the curly bracket notation ({}
), with the keys and values separated by a colon (:
) and each pair separated by a comma (,
).
gistlibby LogSnag