我想创建一个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)
}
Run Code Online (Sandbox Code Playgroud)
Nic*_*ood 99
每当我想要使用时,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])
}
Run Code Online (Sandbox Code Playgroud)
Sam*_*ton 18
我最喜欢的声明切片贴图的语法:
mapOfSlices := map[string][]string{
"first": {},
"second": []string{"one", "two", "three", "four", "five"},
"third": []string{"quarter", "half"},
}
Run Code Online (Sandbox Code Playgroud)
你写的东西在技术上没有任何不正确之处,但你应该定义自己的类型map[string]*list.List以避免一些陷阱,比如尝试.Front()在nil指针上调用方法.或者map[string]list.List避免这种情况.list.List只是一对指针和一个长度值; 在地图中使用list.List指针只是在空列表的情况下添加nil指针的额外情况.在任何一种情况下,您都应该为此用例定义一个新结构.
我倾向于这样写:http: //play.golang.org/p/yCTYdGVa5G
| 归档时间: |
|
| 查看次数: |
70339 次 |
| 最近记录: |