4.golang中map的增删改查

map 一种无序的键值对, 它是数据结构 hash 表的一种实现方式。map工作方式就是:定义键和值,并且可以获取,设置和删除其中的值。

声明

// 使用关键字 map 来声明
bMap := map[string]int{"key1": 18}
// 使用make来声明
cMap := make(map[string]int)
cMap["key2"] = 19
fmt.Println("bMap:", bMap)
fmt.Println("cMap:", cMap)

上面程序用两种方式创建了两个 map,运行结果如下:

bMap: map[key1:18]
cMap: map[key2:19]

检索键的值

检索 Map元素的语法为map[key]

aMap := make(map[string]int)
aMap["key1"] = 18
aMap["key2"] = 19
fmt.Println("aMap:", aMap)
fmt.Println("aMapkey2:", aMap["key2"])
fmt.Println("aMapkey3:", aMap["key3"])

当map中不存在该key时,该映射将返回该元素类型的零值。所以以上程序输出为:

aMap: map[key1:18 key2:19]
aMapkey2: 19
aMapkey3: 0 

检索键是否存在

检索键是否存在的语法为value, ok := map[key]

aMap := make(map[string]int)
aMap["key1"] = 18
aMap["key2"] = 19
value, ok := aMap["key3"]
if ok {
	fmt.Println("key3", value)
} else {
	fmt.Println("key3", "no")
}

ok的值为map中是否存在该key,存在为true,反之为false。所以以上程序输出为:key3 no

遍历 Map中的所有元素

可以用for循环的range形式用于迭代 Map的所有元素。

aMap := make(map[string]int)
aMap["key1"] = 18
aMap["key2"] = 19
for key, value := range aMap {
	fmt.Printf("aMap[%s] = %d\n", key, value)
}

以上程序输出为:

aMap[key1] = 18
aMap[key2] = 19

因为 map 是无序的,因此对于程序的每次执行,不能保证使用 for range 遍历 map 的顺序总是一致的,而且遍历的顺序也不完全与元素添加的顺序一致。

从 Map中删除元素

delete(map, key) 用于删除 map 中的键。delete 函数没有返回值。

aMap := make(map[string]int)
aMap["key1"] = 18
aMap["key2"] = 19
fmt.Println("map before deletion", aMap)
delete(aMap, "key1")
fmt.Println("map after deletion", aMap)

以上程序输出为:

map before deletion map[key1:18 key2:19]
map after deletion map[key2:19]
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

初辰ge

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值