To initialize a map with key-value pairs in Go, you can use the following methods:
Method 1: Using a Composite Literal
myMap := map[keyType]valueType{
key1: value1,
key2: value2,
key3: value3,
// add more key-value pairs as needed
}
Replace keyType
with the data type of the keys and valueType
with the data type of the values. Then assign key-value pairs within the braces {}
.
Example:
myMap := map[string]int{
"apple": 1,
"banana": 2,
"orange": 3,
}
Method 2: Using the make
function
myMap := make(map[keyType]valueType)
myMap[key1] = value1
myMap[key2] = value2
myMap[key3] = value3
Create an empty map using the make
function, then assign values to individual keys using the =
assignment operator.
Example:
myMap := make(map[string]int)
myMap["apple"] = 1
myMap["banana"] = 2
myMap["orange"] = 3
Both methods will initialize a map with the provided key-value pairs. Choose the method that suits your specific use case and preference.