記一次坑爹的golang 二維map判斷問題

yinnnnnnn發表於2018-10-18

現象

貼程式碼:

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
}

相關文章