add a key and value to a map in go

To add a key-value pair to a map in Go, you can simply use the following syntax:

main.go
myMap := make(map[string]int)
myMap["apple"] = 2
49 chars
3 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.go
myMap := map[string]int{"apple": 2, "orange": 3, "banana": 1}
62 chars
2 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