Created
April 15, 2019 14:42
-
-
Save 5idu/3008986afcd9f3e6f9404101b60d01d9 to your computer and use it in GitHub Desktop.
map小知识点
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### Map | |
- map是基于散列表来实现,就是我们常说的Hash表 | |
- map存储的是无序的键值对集合 | |
- map的key,可以重复,如果重复了,则相当于覆盖,后面覆盖前者 | |
- map中的key可以是很多种类型,比如bool、数字、string、指针等,但是含有切片或函数的复杂类型则不能作为键使用,因为这几个没法用 == 来判断 | |
- 对于map的值来说,就没有什么限制了,切片这种在键里不能用的,完全可以用在值里 | |
```go | |
func main() { | |
var m map[int]string | |
m[0] = "a" | |
m[1] = "b" | |
m[0] = "c" | |
fmt.Println(m) | |
} | |
// Output: | |
panic: assignment to entry in nil map | |
``` | |
- 一个nil的Map是未初始化的,但是这样我们是不能操作存储键值对的 | |
- 只有使用map字面量,或者使用make函数分配内存后,才可以使用 | |
```go | |
func main() { | |
dict := map[string]int{"王五": 60, "张三": 43} | |
modify(dict) | |
fmt.Println(dict["张三"]) | |
} | |
func modify(dict map[string]int) { | |
dict["张三"] = 10 | |
} | |
// Output: | |
10 | |
``` | |
- 如果一个map传递给一个函数,该函数对这个map做了修改,那么这个map的所有引用,都会感知到这个修改 | |
- 可以证明传递的并不是一个map的副本,这个特性和切片是类似的,这样性能就会更高,因为复制整个map的代价太大了 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment