1 package main 2 3 import "fmt" 4 5 //Map 6 //创建:make(map[string]int) 7 //获取元素: m[key] 8 //key不存在时,获得value类型的初始值 9 //用value, ok:= m[key]来判断是否存在key10 //delete删除元素11 //用range遍历key,或者遍历key,value对12 //不保证遍历顺序,如需顺序,需手动对key排序13 //用len获得元素个数14 //map使用哈希表,必须可以比较相等15 //除了slice, map, function的内建类型都可以作为key16 //struct类型不包含上述字段也可以作为key17 18 func main() {19 //创建map20 m := map[string] string {21 "name": "ccmouse" ,22 "course": "golang",23 "site": "imooc",24 "quality": "notbad",25 }26 fmt.Println(m) //map[course:golang site:imooc quality:notbad name:ccmouse]27 28 m2 := make( map[string]int)29 fmt.Println(m2) //map[] m2 == empty map30 31 var m3 map[string]int32 fmt.Println(m3) //map[] m3 == nil33 34 //map的遍历35 for k, v := range m{36 fmt.Println(k, v) //name ccmouse //hash map输出无序37 //course golang38 //site imooc39 //quality notbad40 }41 42 //map取值43 courseName, ok := m["course"]44 fmt.Println(courseName, ok) //golang true45 46 if causeName, ok:= m["cause"]; ok{ //判断值存不存在47 fmt.Println(causeName)48 }else{49 fmt.Println("Key does not exist") //Key does not exist50 }51 52 //删除元素53 name, ok := m["name"]54 fmt.Println(name, ok) //ccmouse true55 delete(m, "name")56 name, ok = m["name"]57 fmt.Println(name, ok) // false58 }