To create a map with slices as values in Go, follow these steps:
map[keyType][]valueType
. For example, to create a map with string
keys and int
slices as values, use map[string][]int
.make()
function.Here's an example code snippet that demonstrates the process:
package main
import "fmt"
func main() {
// Declare and initialize the map
myMap := make(map[string][]int)
// Add pairs of key-value
myMap["key1"] = append(myMap["key1"], 1) // Appending a new value
myMap["key2"] = append(myMap["key2"], 2, 3)
myMap["key1"] = append(myMap["key1"], 4) // Appending another new value to an existing key
// Accessing the values of a specific key
fmt.Println(myMap["key1"]) // Output: [1 4]
fmt.Println(myMap["key2"]) // Output: [2 3]
}
In the above example, we create a map myMap
with string
keys and int
slices as values. We add pairs of key-value to the map and append new values to existing keys. Finally, we access the values of specific keys using the key in the square bracket notation and print them.