fmt.Printf("Map literal at \"one\" is: %d\n", mapLit["one"]) fmt.Printf("Map created at \"key2\" is: %f\n", mapCreated["key2"]) fmt.Printf("Map assigned at \"two\" is: %d\n", mapLit["two"]) fmt.Printf("Map literal at \"ten\" is: %d\n", mapLit["ten"]) }
/* Output: Map literal at "one" is: 1 Map created at "key2" is: 3.141590 Map assigned at "two" is: 3 Map literal at "ten" is: 0 */
map1 := make(map[string]int) map1["New Delhi"] = 55 map1["Beijing"] = 20 map1["Washington"] = 25 value, isPresent = map1["Beijing"] if isPresent { fmt.Printf("The value of \"Beijing\" in map1 is: %d\n", value) } else { fmt.Printf("map1 does not contain Beijing") }
value, isPresent = map1["Paris"] fmt.Printf("Is \"Paris\" in map1 ?: %t\n", isPresent) fmt.Printf("Value is: %d\n", value)
// delete an item: delete(map1, "Washington") value, isPresent = map1["Washington"] if isPresent { fmt.Printf("The value of \"Washington\" in map1 is: %d\n", value) } else { fmt.Println("map1 does not contain Washington") } } /*output The value of "Beijing" in map1 is: 20 Is "Paris" in map1 ?: false Value is: 0 map1 does not contain Washington */
for key := range map1 { fmt.Printf("key is: %d\n", key) }
实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
package main import"fmt"
funcmain() { map1 := make(map[int]float32) map1[1] = 1.0 map1[2] = 2.0 map1[3] = 3.0 map1[4] = 4.0 for key, value := range map1 { fmt.Printf("key is: %d - value is: %f\n", key, value) } } /*output key is: 3 - value is: 3.000000 key is: 1 - value is: 1.000000 key is: 4 - value is: 4.000000 key is: 2 - value is: 2.000000 */
这里可以看到输出并不是按照顺序的,也就是说不是按照key or value进行排列。map 和数据结构中的hash,python中的dict一样,拿来计数就可以了,如果为了规则索引还是去用slice吧。(这里不免想到leetcode上很多题需要用一个hash或者dict来计数,那go在做题的时候直接用map就好咯)
// main函数是程序的入口,演示了两种不同的方式来初始化和修改切片中的映射 funcmain() { // Version A: // 创建一个包含5个映射的切片,并初始化每个映射 items := make([]map[int]int, 5) for i:= range items { items[i] = make(map[int]int, 1) items[i][1] = 2 } fmt.Printf("Version A: Value of items: %v\n", items)
// Version B: NOT GOOD! // 创建一个包含5个映射的切片,尝试初始化每个映射,但这种方式是错误的 items2 := make([]map[int]int, 5) for _, item := range items2 { item = make(map[int]int, 1) // item is only a copy of the slice element. item[1] = 2// This 'item' will be lost on the next iteration. } fmt.Printf("Version B: Value of items: %v\n", items2) } /*ooutput Version A: Value of items: [map[1:2] map[1:2] map[1:2] map[1:2] map[1:2]] Version B: Value of items: [map[] map[] map[] map[] map[]] */