map的定义
map[KeyType]ValueType
KeyType为键的类型,ValueType为值的类型
map 初始化
m1 := make(map[int]int)
fmt.Println(m1) // map[]
m2 := make(map[int]int,1)
make初始化的时候,可以不指定map容量,也可以指定容量
判断map是否存在某个值
package main
import "fmt"
func main() {
m1 := make(map[int]int)
m1[1] = 1
m1[2] = 2
v, ok := m1[1] // 返回两个值,后面的bool值就是判断map是否存在 1 这个值
if ok {
fmt.Println(v)
} else {
fmt.Println("without this key")
}
}
Map的value赋值
package main
import (
"fmt"
)
type S struct {
s string
}
func main() {
intmap := make(map[int]int, 0)
intmap[1] = 1
fmt.Println(intmap[1]) //1
intmap[1] = 2
fmt.Println(intmap[1]) //2
structMap := make(map[int]S, 0)
tmps := S{s: "tmp1"}
structMap[1] = tmps
fmt.Println(structMap[1]) //tmp1
structMap[1].s = "tmp2"
fmt.Println(structMap[1]) //cannot assign to struct field structMap[1].s in map
}
报错原因:map[int]S的value是一个Student结构值,所以当structMap[1].s = "tmp2"是一个值拷贝过程。而structMap[1]则是一个值引用。那么值引用的特点是 只读 。
修改方式1:
tmps1 := structMap[1]
tmps1.s = "tmp2"
structMap[1] = tmps1
fmt.Println(structMap[1])
先做一次值拷贝,做出一个tmps1副本
,然后修改该副本,然后再次发生一次值拷贝复制回去,structMap[1] = tmps1,但是这种会在整体过程中发生2次结构体值拷贝