使用映射
Go 中的映射是一个哈希表,是键值对的集合。 映射中所有的键都必须具有相同的类型,它们的值也是如此。 不过,可对键和值使用不同的类型。 例如,键可以是数字,值可以是字符串。 若要访问映射中的特定项,可引用该项的键。
声明和初始化映射
package main
import "fmt"
func main() {
studentsAge := map[string]int{
"john": 32,
"bob": 31,
}
fmt.Println(studentsAge)
}
如果不想使用项来初始化映射,可使用内置函数 make() 在上一部分创建映射。 可使用以下代码创建空映射:
studentsAge := make(map[string]int)
添加项
package main
import "fmt"
func main() {
studentsAge := make(map[string]int)
studentsAge["john"] = 32
studentsAge["bob"] = 31
fmt.Println(studentsAge)
}
访问项
在 Go 中,映射的下标表示法可生成两个值。 第一个是项的值。 第二个是指示键是否存在的布尔型标志。
package main
import "fmt"
func main() {
studentsAge := make(map[string]int)
studentsAge["john"] = 32
studentsAge["bob"] = 31
age, exist := studentsAge["christy"]
if exist {
fmt.Println("Christy's age is", age)
} else {
fmt.Println("Christy's age couldn't be found")
}
}
输出
Christy's age couldn't be found
删除项
若要从映射中删除项,请使用内置函数 delete()。 下例演示了如何从映射中删除项:
package main
import "fmt"
func main() {
studentsAge := make(map[string]int)
studentsAge["john"] = 32
studentsAge["bob"] = 31
delete(studentsAge, "christy")
fmt.Println(studentsAge)
}
输出
map[bob:31 john:32]
果你尝试删除不存在的项,Go 不会执行 panic。
映射中的循环
将键保存在 name
变量中,将值保存在 age
变量中。 因此,range
会首先生成项的键,然后再生成该项的值。 可使用 _
变量忽略其中任何一个,如下例所示:
package main
import (
"fmt"
)
func main() {
studentsAge := make(map[string]int)
studentsAge["john"] = 32
studentsAge["bob"] = 31
for _, age := range studentsAge {
fmt.Printf("Ages %d\n", age)
}
}
因为,range
会首先生成项的键,然后再生成该项的值。所以,也可以这样
package main
import (
"fmt"
)
func main() {
studentsAge := make(map[string]int)
studentsAge["john"] = 32
studentsAge["bob"] = 31
for name := range studentsAge {
fmt.Printf("Names %s\n", name)
}
}
输出
Names john
Names bob