创建一个字符串到列表的映射

huangapple go评论80阅读模式
英文:

Create a map of string to List

问题

我想创建一个从字符串到container/list.List实例的映射。这样做的方式正确吗?

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)
}
英文:

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

答案1

得分: 191

每当我想使用List时,我发现切片是正确的选择,例如

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])
}
英文:

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

得分: 43

我最喜欢的声明字符串到字符串切片的映射的语法是:

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

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

答案3

得分: 8

你写的代码在技术上没有问题,但是你应该定义自己的类型,围绕map[string]*list.List,以避免一些陷阱,比如试图在空指针上调用.Front()方法。或者将其定义为map[string]list.List以避免这种情况。list.List只是一对指针和一个长度值;在你的map中使用list.List指针只是在空列表的情况下添加了一个空指针的额外情况。无论哪种情况,你都应该为这种用例定义一个新的结构体。

我倾向于这样写:
http://play.golang.org/p/yCTYdGVa5G

英文:

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

huangapple
  • 本文由 发表于 2012年10月2日 01:18:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/12677934.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定