[Bug] Fix wrong contents of 8.4 and add sample code

This commit is contained in:
dbarobin
2015-08-07 10:54:12 +08:00
parent 884d3fae98
commit 06cb303d80
2 changed files with 24 additions and 3 deletions

View File

@@ -1,8 +1,8 @@
# 8.3 map 类型的切片 # 8.4 map 类型的切片
假设我们想获取一个 map 类型的切片,我们必须使用两次 `make()` 函数,第一次分配切片,第二次分配 切片中每个 map 元素(参见下面的例子 8.3)。 假设我们想获取一个 map 类型的切片,我们必须使用两次 `make()` 函数,第一次分配切片,第二次分配 切片中每个 map 元素(参见下面的例子 8.4)。
示例 8.3 [maps_forrange.go](examples/chapter_8/maps_forrange.go) 示例 8.4 [maps_forrange2.go](examples/chapter_8/maps_forrange2.go)
```go ```go
package main package main

View File

@@ -0,0 +1,21 @@
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)
}