Problem:
You want to create a Map with keys of type string and values of type List. Is the following code snippet the correct approach:
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) }
Answer:
The code snippet you provided does create a Map of string to List, but it may not be the most efficient approach. When working with Lists in Go, slices are generally a more suitable choice due to their performance advantages.
Using Slices:
The following code snippet demonstrates how to use slices instead of Lists:
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]) }
Benefits of Using Slices:
Slices offer several advantages over Lists, including:
The above is the detailed content of Is Using `list.List` the Best Way to Create a Go Map with String Keys and List Values?. For more information, please follow other related articles on the PHP Chinese website!