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]来判断是否存在key 10 //delete删除元素 11 //用range遍历key,或者遍历key,value对 12 //不保证遍历顺序,如需顺序,需手动对key排序 13 //用len获得元素个数 14 //map使用哈希表,必须可以比较相等 15 //除了slice, map, function的内建类型都可以作为key 16 //struct类型不包含上述字段也可以作为key 17 18 func main() { 19 //创建map 20 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 map 30 31 var m3 map[string]int 32 fmt.Println(m3) //map[] m3 == nil 33 34 //map的遍历 35 for k, v := range m{ 36 fmt.Println(k, v) //name ccmouse //hash map输出无序 37 //course golang 38 //site imooc 39 //quality notbad 40 } 41 42 //map取值 43 courseName, ok := m["course"] 44 fmt.Println(courseName, ok) //golang true 45 46 if causeName, ok:= m["cause"]; ok{ //判断值存不存在 47 fmt.Println(causeName) 48 }else{ 49 fmt.Println("Key does not exist") //Key does not exist 50 } 51 52 //删除元素 53 name, ok := m["name"] 54 fmt.Println(name, ok) //ccmouse true 55 delete(m, "name") 56 name, ok = m["name"] 57 fmt.Println(name, ok) // false 58 }