go map 学习

什么是map

map 是在go 中将值(value) 与 键(key) 关联的内置类型,通过相应的键可以获取到值
定义类型为 map[key]value

一、 创建map

```

package main
import "fmt"
func maptest() {
// 1、声明方式1 map
map2 :=map[int] string{1:"hello",2:"world"}
fmt.Println(map2)
// 输出
map2 :=map[int] string{1:"hello",2:"world"}
fmt.Println(map2)

//2、声明方式2  声明一个空map 

map2 :=map[int] string{}
fmt.Println(map2) 
// 输出
map[]

// 3、 声明方式3 使用make 声明一个map,
map3 :=make(map [int]int,10)
fmt.Println(map3)
// 输出
map[] 0

}

func main()  {
maptest()

}

二、map 的获取

// 1、遍历获取
for k,v :=range map1{
fmt.Println(k,v)
}

// 输出

1 key1

2 key2
3 key3

//2、判断map 中key 值是否存在

if v,has :=map1[1];has{
    fmt.Println("value=",v,"has=",has)
} else{
    fmt.Println("value=",v,"has=",has)
    // 输出

    value= key1 has= true

三、map 删除

// 1、删除
fmt.Println("begin delete")
delete (map1,1)
for k,v :=range map1{
fmt.Println(k,v)
}

 // 输出
 2 key2
3 key3

2、 修改
map1[1]="hello"
map1[4]="world"

for k,v :=range map1{
    fmt.Println(k,v)
}

// 输出

 4 world
 1 hello
 2 key2
3 key3

猜你喜欢

转载自blog.51cto.com/sdsca/2465125