go语言中map使用哈希表,必须可以比较相等
除了slice,map,function的内建类型都可以作为key
Struct类型不包括上述字段,也可作为key
map中的key是无序的
package main import ( "fmt" "sort" ) var ( barVal = map[string]int{"alpha": 34, "bravo": 56, "charlie": 23, "delta": 87, "echo": 56, "foxtrot": 12, "golf": 34, "hotel": 16, "indio": 87, "juliet": 65, "kili": 43, "lima": 98} ) func main() { m:=map [string]string { "name":"fyf", "course":"golang", "site":"imooc", "quality":"notbad", } m2:=make(map[string]int)//空map一般就用make定义 m2==empty map var m3 map[string]string//m3 == nil fmt.Println(m,m2,m3) fmt.Println("") //map的遍历 fmt.Println("map的遍历") for k,v :=range m{ fmt.Println(k,v) } fmt.Println("") //mao的操作 fmt.Println("得到value") //如果map中的key不存在,则会得到一个nil值 courseName:=m["course"] fmt.Println(courseName) //判断key是否存在map中 courseName2,ok:=m["course"] fmt.Println(courseName2,ok) if couseName,ok:=m["couse"]; ok{ fmt.Println(couseName) }else { fmt.Println("key 不存在") } fmt.Println("") fmt.Println("删除value") name,ok:=m["name"] fmt.Println(name,ok) delete(m,"name") name,ok = m["name"] fmt.Println(name,ok) fmt.Println("unsorted:") for k, v := range barVal { fmt.Printf("Key: %v, Value: %v / ", k, v) } keys := make([]string, len(barVal)) i := 0 for k, _ := range barVal { keys[i] = k//往数组里面放值 i++ } fmt.Println("") fmt.Println("") fmt.Println(keys) sort.Strings(keys) fmt.Println() fmt.Println("sorted:") for _, k := range keys { fmt.Printf("Key: %v, Value: %v / ", k, barVal[k]) } fmt.Println("") fmt.Println("") items := make([]map[int]int, 5) for i:= range items { items[i] = make(map[int]int, 1) items[i][1] = 2//key is 1, value is 2 } fmt.Printf("Version A: Value of items: %v ", items) }