Create a map of string to List

Go

Go Problem Overview


I'd like to create a map of string to 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)
}

Go Solutions


Solution 1 - Go

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

Solution 2 - Go

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"},
}

Solution 3 - Go

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCarsonView Question on Stackoverflow
Solution 1 - GoNick Craig-WoodView Answer on Stackoverflow
Solution 2 - GoSam HoustonView Answer on Stackoverflow
Solution 3 - GojorelliView Answer on Stackoverflow