我嘗試編寫一個驗證數據的函數??聪旅娴拇a:func Create(name, email, password, local string, termOf bool) map[string]string { wait := new(sync.WaitGroup) mutex := new(sync.Mutex) errMsg := make(map[string]string) if !termOf { mutex.Lock() errMsg["termOf"] = translate(local, "text06") mutex.Unlock() } wait.Add(1) go func() { err := ValidateName(name, local) mutex.Lock() errMsg["name"] = err.Error() mutex.Unlock() wait.Done() }() wait.Add(1) go func() { err := ValidateEmail(email, local) mutex.Lock() errMsg["email"] = err.Error() mutex.Unlock() wait.Done() }() wait.Add(1) go func() { err := ValidatePassword(password, local) mutex.Lock() errMsg["password"] = err.Error() mutex.Unlock() wait.Done() }() wait.Wait() // If errors appear if len(errMsg) > 0 { return errMsg } return nil}正如你在這里看到的,我使用了三個 goroutines 并且在 goroutine 中我鎖定它以更改 errMsg 變量映射類型。當我運行該函數時,出現編譯器錯誤runtime error: invalid memory address or nil pointer dereference[signal 0xc0000005 code=0x0 addr=0x14 pc=0x44206a]但是當我在 goroutine 中刪除所有 errMsg 插入時,該函數就可以工作了。我不知道我做錯了什么。
1 回答

Smart貓小萌
TA貢獻1911條經驗 獲得超7個贊
可能err是nil從ValidateName(),ValidateEmail()或ValidatePassword()調用返回時。
您應該err != nil在將其添加到地圖之前進行檢查。
if err != nil {
mutex.Lock()
errMsg["xxx"] = err.Error()
mutex.Unlock()
}
換句話說,這不是問題所在的地圖errMsg,而是您想要放入其中的值。
- 1 回答
- 0 關注
- 191 瀏覽
添加回答
舉報
0/150
提交
取消