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:
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3