Create a Golang map of Lists

2019-01-17 05:44发布

问题:

I'd like to create a map of container/list.List instances. Is this the correct way to go about it?

package main

import (
    "fmt"
    "container/list"
)

func main() {
    x := make(map[string]*list.List)

    x["key"] = list.New()
    x["key"].PushBack("value")

    fmt.Println(x["key"].Front().Value)
}

回答1:

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])
}


回答2:

My favorite syntax for declaring a map of slices:

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


回答3:

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



标签: go