1.基础定义
golang中的map如同它的函数一样"纯粹",map就是用来存储键值对的容器,别管什么哈希不哈希的(底层已实现),用就行
//创建一个map
m := map[string]string{
"name": "Tony",
"age": "22",
"title": "FashionDirector",
}
//复合map
mm := make(map[string]map[string]string) //make出来的mm == empty
var mm1 map[string]map[string]string //直接var出来的mm1 == nil,使用时需要用'make()'初始化
//取值
m["name"]
2.特性和操作
由于底层实际是HashMap,所以遍历出来的结果是'无序'的
取值时,如果key不存在,那么会得到value的变量类型初始值
在'buildin.go'中提供(内置)了'delete(m map[Type]Type1, key Type)'函数来删除map中的值
m := map[string]string{
"name": "Tony",
"age": "22",
"title": "FashionDirector",
}
//value为"",ok为false
value,ok := m["alias"]
//删除值
delete(m,"age")
测试代码
package main
import "fmt"
func testMap() {
//单map
m := map[string]string{
"name": "Tony",
"age": "22",
"title": "FashionDirector",
}
//复合map
mm := make(map[string]map[string]string) //make出来的mm == empty
mm["The Fashion World"] = m
var mm1 map[string]map[string]string //直接var出来的mm1 == nil,使用时需要用'make()'初始化
//直接使用会造成runtime panic:assignment to entry in nil map
//mm1["The New York International"] = m
mm1= make(map[string]map[string]string )
if mm1["The New York International"] == nil {
mm1["The New York International"] = make(map[string]string)
}
mm1["The New York International"]["name"] = "Kevin"
//取值
fmt.Println(m)
fmt.Println(mm)
fmt.Println(mm["The Fashion World"]["name"])
fmt.Println(mm1)
//验证key是否存在
if value,ok := mm1["The New York International"]["age"];ok{
fmt.Println(value)
}else {
fmt.Println("The key not exist")
}
//遍历map
for k,v := range m{
fmt.Println(k,v)
}
//删除key-value
value,ok := m["age"]
fmt.Println(value,ok)
delete(m,"age")
value,ok = m["age"]
fmt.Println(value,ok)
}
func main() {
testMap()
}