Files
the-way-to-go_ZH_CN/eBook/08.4.md
2013-11-26 11:35:07 +08:00

37 lines
1.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#8.3 map分片
假设我们想获取一个map的分片我们必须使用两次make()方法第一次分配slice第二次分配slice的每个map元素参见下面的例子8.3)。
示例 8.3 [maps_forrange.go](exmaples/chapter_8/maps_forrange.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版本那样通过索引使用slice的map项。在B版本中获得的项只是map值的一个拷贝而已所以真正的map元素没有得到初始化。
##链接
- [目录](directory.md)
- 上一节:[for循环构造方法](08.3.md)
- 下一节:[map排序](08.5.md)