记一次坑爹的golang 二维map判断问题
现象
var PeopleLimit =make(map[string]map[string]int64)
func foo(arr1,arr2 string){
if x,ok := PeopleLimit[arr1][arr2];ok{
fmt.Println(" ok")
fmt.Println(x)
}else{
PeopleLimit[arr1] = make(map[string]int64)
fmt.Println(" not ok")
}
//添加新元素
PeopleLimit[arr1][arr2] = time.Now().Unix()
}
func main() {
foo("a","b")
foo("c","d")
foo("a","f")
fmt.Println(PeopleLimit)
return
}
按理应该要输出三个元素,但第一个被覆盖了,定位了很久才发现是二维map的判断问题:
执行foo("a","f")
时if x,ok := PeopleLimit[arr1][arr2];
判断是二级key也不存在,但在执行第三次foo("a","f")
时,map[a][b]
是存在,但map[a][f]
不存在,于是,进入else后重新make
将map[a]
清空了!!
修改后:
var PeopleLimit =make(map[string]map[string]int64)
func foo(arr1,arr2 string){
if x,ok := PeopleLimit[arr1];ok{
//修改点
if y,ok := x[arr2];ok{
fmt.Println(" ok")
fmt.Println(x,y)
}
}else{
PeopleLimit[arr1] = make(map[string]int64)
fmt.Println(" not ok")
}
//添加新元素
PeopleLimit[arr1][arr2] = time.Now().Unix()
}
func main() {
foo("a","b")
foo("c","d")
foo("a","f")
fmt.Println(PeopleLimit)
return
}
---------------------
作者:yinnnnnnn
来源:CSDN
原文:https://blog.csdn.net/qq_35440678/article/details/83154780
版权声明:本文为博主原创文章,转载请附上博文链接!