Golang Maps(Aka HashMap)及示例
Go 提供了实现哈希表的内置映射类型Map。Golang 映射是无序的数据集,可以用来存储键/值对中的数据。因为它是一个无序集合,这意味着无法预测 键/值 对返回的顺序。
一个简单的 map 声明如下所示-
其中 KeyType 可以是任何可比较(comparable) 的类型。 ValueType 可以是任何类型。
让我们看一个使用 Golang Map 的简单示例。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
| package main
import (
"fmt"
)
func main() {
// Creating a HashMap of String and Integer
var animal = make(map[string]int)
// Inserting values in hashmap
animal["Dog"] = 10
animal["Cat"] = 13
animal["Fish"] = 20
// Iterating Hashmap
for key, value := range animal {
fmt.Println("We have", value, key)
}
// Getting Value corresponding to Key
fmt.Println("Total Dogs ", animal["Dog"])
var sum int = 0
// Performing operation on hashmap
for _, value := range animal {
sum += value
}
fmt.Println("Total pets ", sum)
}
|
1
2
3
4
5
6
| Output :
We have 20 Fish
We have 10 Dog
We have 13 Cat
Total Dogs 10
Total pets 43
|
Compiling & Running
手动编译源代码:
1
2
| $ go build hash.go
$ ./hash
|
无需手动编译即可运行:
更多关于 Golang Map 的资料
要使用一些数据初始化映射,我们可以使用如下的映射文本
1
2
3
4
5
6
| colorCode := map[string]int{
"red": 3711,
"black": 2138,
"pink": 1908,
"green": 912,
}
|
当使用任何一种循环时,我们都不能预测 Golang Map的迭代顺序。当在 map 上迭代时,我们可能得到与前一个输出不同的输出。有必要指出,Golang Map不宜同时使用。当我们试图同时读写它们时会发生什么并没有定义。
Deleting keys from Golang maps
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
| package main
import (
"fmt"
)
func main() {
// Creating a HashMap of String and Integer
var colorCode = make(map[string]int)
// Inserting values in hashmap
colorCode["Red"] = 2
colorCode["Blue"] = 4
colorCode["Green"] = 8
colorCode["Orange"] = 16
colorCode["Violet"] = 32
colorCode["Pink"] = 64
colorCode["Yellow"] = 128
// Iterating Hashmap
for key, value := range colorCode {
fmt.Println("We have", value, key)
}
// Deleting values
delete(colorCode, "Violet")
fmt.Println("------After Deletion------")
for key, value := range colorCode {
fmt.Println("We now have", value, key)
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| We have 4 Blue
We have 8 Green
We have 16 Orange
We have 32 Violet
We have 64 Pink
We have 128 Yellow
We have 2 Red
------After Deletion------
We now have 2 Red
We now have 4 Blue
We now have 8 Green
We now have 16 Orange
We now have 64 Pink
We now have 128 Yellow
|
在上面的例子中,我们将紫色从Map的代码中移除。
手动编译源代码:
1
2
| $ go build hashmapEx.go
$ ./hashmapEx
|
无需编译即可运行:
source: Golang Maps (Aka HashMap)