From 884d3fae9829fe8234d83b0dbfcdfd39afe0aef8 Mon Sep 17 00:00:00 2001 From: dbarobin Date: Fri, 7 Aug 2015 10:50:54 +0800 Subject: [PATCH 1/2] [Typo] Fix multiple typos from 07.6 to 08.2 --- eBook/07.6.md | 2 +- eBook/08.2.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/eBook/07.6.md b/eBook/07.6.md index c9bd78b..46e3960 100644 --- a/eBook/07.6.md +++ b/eBook/07.6.md @@ -49,7 +49,7 @@ b = append(b, s...) ## 7.6.4 修改字符串中的某个字符 -Go 语言中的字符串是不可变的,也就是说 `str[index]` 这样的表达式是不可以被放在等号左侧的。如果尝试运行 `str[i] = ‘D’` 会得到错误:`cannot assign to str[i]`。 +Go 语言中的字符串是不可变的,也就是说 `str[index]` 这样的表达式是不可以被放在等号左侧的。如果尝试运行 `str[i] = 'D'` 会得到错误:`cannot assign to str[i]`。 因此,您必须先将字符串转换成字节数组,然后再通过修改数组中的元素值来达到修改字符串的目的,最后将字节数组转换会字符串格式。 diff --git a/eBook/08.2.md b/eBook/08.2.md index 9bf82c3..7e1fdcf 100644 --- a/eBook/08.2.md +++ b/eBook/08.2.md @@ -2,7 +2,7 @@ 测试 map1 中是否存在 key1: -在例子 8.1 中,我们已经见过可以使用 `val1 = map1[key1]` `的方法获取 key1 对应的值 val1。如果 map 中不存在 key1,val1 就是一个值类型的空值。 +在例子 8.1 中,我们已经见过可以使用 `val1 = map1[key1]` 的方法获取 key1 对应的值 val1。如果 map 中不存在 key1,val1 就是一个值类型的空值。 这就会给我们带来困惑了:现在我们没法区分到底是 key1 不存在还是它对应的 value 就是空值。 From 06cb303d807d85766c62085a0095d17798be679c Mon Sep 17 00:00:00 2001 From: dbarobin Date: Fri, 7 Aug 2015 10:54:12 +0800 Subject: [PATCH 2/2] [Bug] Fix wrong contents of 8.4 and add sample code --- eBook/08.4.md | 6 +++--- eBook/examples/chapter_8/maps_forrange2.go | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) create mode 100644 eBook/examples/chapter_8/maps_forrange2.go diff --git a/eBook/08.4.md b/eBook/08.4.md index 2b03e11..e4e9bba 100644 --- a/eBook/08.4.md +++ b/eBook/08.4.md @@ -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 package main diff --git a/eBook/examples/chapter_8/maps_forrange2.go b/eBook/examples/chapter_8/maps_forrange2.go new file mode 100644 index 0000000..f86bbd7 --- /dev/null +++ b/eBook/examples/chapter_8/maps_forrange2.go @@ -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) +}