create a map with a value of type slice in go

In Go, you can create a map with values of type slice by initializing a map with make() and assigning a slice to each key. Here is an example:

main.go
package main

import "fmt"

func main() {
    m := make(map[string][]int)

    m["foo"] = []int{1, 2, 3}
    m["bar"] = []int{4, 5, 6}

    fmt.Println(m)
}
157 chars
13 lines

This program creates a map m with string keys and slice values. Then it assigns two slices of integers to keys "foo" and "bar". Finally, it prints the map which should output:

main.go
map[foo:[1 2 3] bar:[4 5 6]]
29 chars
2 lines

You can modify and access the slices for each key in the same way you would with any regular slice.

related categories

gistlibby LogSnag