标签:-- 空间 ack bbb 自动 增删改 project [1] ring
// code_014_map_operator project main.go
package main
import (
"fmt"
)
func DeleteMap(m map[int]string, key int) {
delete(m, key)
for k, v := range m {
fmt.Printf("len(m)=%d, %d ----> %s\n", len(m), k, v)
}
}
func main() {
//赋值-->修改和追加
m1 := map[int]string{1: "ck_god", 2: "god_girl"}
m1[1] = "xxx"
m1[3] = "lily" //追加,go底层自动为map分配空间
fmt.Println(m1)
m2 := make(map[int]string, 10)
m2[0] = "aaa"
m2[1] = "bbb"
fmt.Println(m2)
fmt.Println(m2[0], m2[1])
fmt.Println("")
//遍历
m3 := map[int]string{1: "ck_god", 2: "god_girl"}
for k, v := range m3 {
fmt.Printf("%d--->>>%s\n", k, v)
}
for k := range m3 {
fmt.Printf("%d--->%s\n", k, m3[k])
}
fmt.Println("")
//获取map的值
value, ok := m3[1]
fmt.Println("value = ", value, ", ok = ", ok)
value2, ok2 := m3[3]
fmt.Println("value2 = ", value2, ", ok2 = ", ok2)
fmt.Println("")
//删除
m4 := map[int]string{1: "ck_god", 2: "god_girl"}
delete(m4, 2) //删除key值为2的map
for k, v := range m4 {
fmt.Printf("%d--->%s\n", k, v)
}
fmt.Println("")
//map作为参数传递
//在函数间传递映射并不会制造出该映射的一个副本,不是值传递,而是引用传递:
m := map[int]string{1: "ck_god", 2: "god_girl", 3: "girl_angle"}
DeleteMap(m, 3)
for k, v := range m {
fmt.Printf("len(m)=%d, %d ----> %s\n", len(m), k, v)
}
}
执行结果如下:
map[1:xxx 2:god_girl 3:lily]
map[1:bbb 0:aaa]
aaa bbb
1--->>>ck_god
2--->>>god_girl
2--->god_girl
1--->ck_god
value = ck_god , ok = true
value2 = , ok2 = false
1--->ck_god
len(m)=2, 1 ----> ck_god
len(m)=2, 2 ----> god_girl
len(m)=2, 1 ----> ck_god
len(m)=2, 2 ----> god_girl
标签:-- 空间 ack bbb 自动 增删改 project [1] ring
原文地址:http://blog.51cto.com/13914991/2293885