7-8 章修改 (#842)

Co-authored-by: Joe Chen <jc@unknwon.io>
This commit is contained in:
Haigang Zhou
2022-05-10 13:53:30 +08:00
committed by GitHub
parent c42d8a340a
commit 30ca13a369
14 changed files with 195 additions and 180 deletions

View File

@@ -1,6 +1,6 @@
# 8.6 将 map 的键值对调
这里对调是指调换 key 和 value。如果 map 的值类型可以作为 key 且所有的 value 是唯一的,那么通过下面的方法可以简单的做到键值对调。
这里对调是指调换 key 和 value。如果 `map` 的值类型可以作为 key 且所有的 value 是唯一的,那么通过下面的方法可以简单的做到键值对调。
示例 8.7 [invert_map.go](examples/chapter_8/invert_map.go)
@@ -34,9 +34,9 @@ func main() {
inverted:
Key: 34, Value: golf / Key: 23, Value: charlie / Key: 16, Value: hotel / Key: 87, Value: delta / Key: 98, Value: lima / Key: 12, Value: foxtrot / Key: 43, Value: kili / Key: 56, Value: bravo / Key: 65, Value: juliet /
如果原始 value 值不唯一那这么做肯定会出问题;这种情况下不会报错,但是当遇到不唯一的 key 时应当直接停止对调,且此时对调后的 map 很可能没有包含原 map 的所有键值对!一种解决方法就是仔细检查唯一性并且使用多值 map比如使用 `map[int][]string` 类型。
如果原始 value 值不唯一那这么做肯定会出问题;这种情况下不会报错,但是当遇到不唯一的 key 时应当直接停止对调,且此时对调后的 `map` 很可能没有包含原 `map` 的所有键值对!一种解决方法就是仔细检查唯一性并且使用多值 `map`,比如使用 `map[int][]string` 类型。
**练习 8.2**
**练习 8.2** [map_drinks.go](exercises\chapter_8\map_drinks.go)
构造一个将英文饮料名映射为法语(或者任意你的母语)的集合;先打印所有的饮料,然后打印原名和翻译后的名字。接下来按照英文名排序后再打印出来。
@@ -44,4 +44,4 @@ func main() {
- [目录](directory.md)
- 上一节:[map 的排序](08.5.md)
- 下一章:[package](09.0.md)
- 下一章:[ (package)](09.0.md)