8.4 map 類型的切片

假設我們想獲取一個 map 類型的切片,我們必須使用兩次 make() 函數,第一次分配切片,第二次分配 切片中每個 map 元素(參見下面的例子 8.4)。

示例 8.4 maps_forrange2.go

package main
import "fmt"

func main() {
    // Version A:
    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!
    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)
}

輸出結果:

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[]]

需要注意的是,應當像 A 版本那樣通過索引使用切片的 map 元素。在 B 版本中獲得的項只是 map 值的一個拷貝而已,所以真正的 map 元素沒有得到初始化。

鏈接

results matching ""

    No results matching ""