How to create a map with slices as values in Go?

To create a map with slices as values in Go, follow these steps:

  1. Declare a map with the desired key type and value type as map[keyType][]valueType. For example, to create a map with string keys and int slices as values, use map[string][]int.
  2. Initialize the map using the make() function.
  3. Add pairs of key-value to the map using the square bracket notation. If the key already exists, append the new value to the existing slice.
  4. Access the values of a specific key using the key in the square bracket notation.

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.