map

来源:互联网 发布:2016赛季林书豪数据 编辑:程序博客网 时间:2024/06/06 00:02

声明

直接上代码:

func main(){    //声明map变量    var testMap map[int] string    if testMap == nil {        fmt.Println("map is nil")    }    //直接使用    testMap[1] = "test1"    testMap[2] = "test2"    fmt.Println("map:", testMap)}

运行结果:

winterdeMacBook-Pro:test winter$ go build mapTest.gowinterdeMacBook-Pro:test winter$ ./mapTestmap is nilpanic: assignment to entry in nil mapgoroutine 1 [running]:main.main()        /Users/winter/code/go_project/src/test/mapTest.go:14 +0x66

结论:
- 声明的map变量是nil,不可以直接使用,必须要初始化

初始化、定义

可以通过make初始化

package mainimport (    "fmt")func main(){    //声明map变量    var testMap map[int] string    if testMap == nil {        fmt.Println("map is nil")    }    //初始化    testMap = make(map[int] string)    testMap[1] = "test1"    testMap[2] = "test2"    fmt.Println("map:", testMap)}

运行结果:

winterdeMacBook-Pro:test winter$ go build mapTest.gowinterdeMacBook-Pro:test winter$ ./mapTestmap is nilmap: map[1:test1 2:test2]

也可以直接定义:

mapTest := make(map[int] string)

增加元素

直接插入key-value

testMap[1] = "chen"

查找

_, ok := testMap[1]if ok {    fmt.Printf("key:%d, value:%s\n", 1, testMap[1])} else {    fmt.Printf("key %d not exsit\n", 1)}

遍历

通过range来遍历

for k, v := range testMap {    fmt.Printf("key:%d, value:%s\n", k, v)}

删除

直接delete

delete(testMap, 1)
原创粉丝点击