记一次坑爹的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后重新makemap[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
}

你可能感兴趣的:(golang)