Go 语言Map(集合)
warning:
这篇文章距离上次修改已过281天,其中的内容可能已经有所变动。
在 Go 语言中,map 是一种内置的数据类型,它可以存储任意类型的无序的键值对。
以下是 Go 语言中 Map 的一些常见操作:
- 声明 Map
声明一个 map 需要指定键和值的类型。这里,我们使用字符串作为键,整数作为值。
var map1 map[string]int
map1 = make(map[string]int)
- 向 Map 添加元素
map1["one"] = 1
map1["two"] = 2
map1["three"] = 3
- 从 Map 中删除元素
delete(map1, "one") // 删除键为 "one" 的元素
- 遍历 Map
Go 语言中遍历 map 的标准方法是使用 for-range 循环。
for key, value := range map1 {
fmt.Printf("Key: %s, Value: %d\n", key, value)
}
- 检查 Map 中是否存在某个键
Go 语言中,我们可以通过判断该键是否存在来判断该键值对是否在 Map 中。
value, ok := map1["two"]
if ok {
fmt.Printf("Key 'two' exists with value %d\n", value)
} else {
fmt.Println("Key 'two' does not exist")
}
- 使用值类型为指针的 Map
var map2 map[string]*int
map2 = make(map[string]*int)
a := 1
map2["one"] = &a
以上就是 Go 语言中 Map 的一些基本操作。
评论已关闭