Golang-Map

251 阅读2分钟

生成

定义 var m map[string]int

初始化m = make(map[string]int),可以不需要定义直接初始化,map必须通过make初始化。

初始化 + 赋值:

m3 := map[string]string{
        "a": "aa",
        "b": "bb",
}

key的类型

As mentioned earlier, map keys may be of any type that is comparable. The language spec defines this precisely, but in short, comparable types are boolean, numeric, string, pointer, channel, and interface types, and structs or arrays that contain only those types. Notably absent from the list are slices, maps, and functions; these types cannot be compared using ==, and may not be used as map keys.

map 可以拷贝吗?

map 其实是不能拷贝的,如果想要拷贝一个 map ,只有一种办法就是循环赋值,就像这样

originalMap := make(map[string]int)
originalMap["one"] = 1
originalMap["two"] = 2
// Create the target map
targetMap := make(map[string]int)
// Copy from the original map to the target map
for key, value := range originalMap {
    targetMap[key] = value
}

如果 map 中有指针,还要考虑深拷贝的过程

originalMap := make(map[string]*int)
var num int = 1
originalMap["one"] = &num
// Create the target map
targetMap := make(map[string]*int)
// Copy from the original map to the target map
for key, value := range originalMap {
var tmpNum int = *value
    targetMap[key] = &tmpNum
}

Map中Value为结构体

无法直接更新

如果想要更新 map 中的value,可以通过赋值来进行操作

map["one"] = 1

但如果 value 是一个结构体,可以直接替换结构体,但无法更新结构体内部的值

originalMap := make(map[string]Person)

originalMap["minibear2333"] = Person{age: 26}

originalMap["minibear2333"].age = 5

会报下面这个错误

★ Cannot assign to originalMap["minibear2333"].age

简单来说就是map不是一个并发安全的结构,所以,并不能修改他在结构体中的值。

修改办法

  • 1.创建临时变量
  • 2.Value使用结构体指针

1.创建个临时变量,做拷贝,像这样

tmp := m["foo"]
tmp.x = 4
m["foo"] = tmp

2.要么直接用指针,比较方便

originalPointMap := make(map[string]*Person)
originalPointMap["minibear2333"] = &Person{age: 26}
originalPointMap["minibear2333"].age = 5

尽量使用结构体切片代替字典切片

jishuin.proginn.com/p/763bfbd36…

谨慎使用map[string]interface{}做参数

jishuin.proginn.com/p/763bfbd36…