Create a map of string to List

Whenever I've wanted to use a List I've found that a slice was the right choice, eg

package main

import "fmt"

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

    x["key"] = append(x["key"], "value")
    x["key"] = append(x["key"], "value1")

    fmt.Println(x["key"][0])
    fmt.Println(x["key"][1])
}

My favorite syntax for declaring a map of string to slice of string:

mapOfSlices := map[string][]string{
    "first": {},
    "second": []string{"one", "two", "three", "four", "five"},
    "third": []string{"quarter", "half"},
}

there's nothing technically incorrect about what you've written, but you should define your own type around map[string]*list.List to avoid some pitfalls, like trying to call the .Front() method on a nil pointer. Or make it a map[string]list.List to avoid that situation. A list.List is just a pair of pointers and a length value; using a list.List pointer in your map just adds the extra case of a nil pointer on top of the case of an empty list. In either situation, you should define a new struct for this use case.

I would be inclined to write it like this: http://play.golang.org/p/yCTYdGVa5G

Tags:

Go