2 回答

TA貢獻1828條經驗 獲得超3個贊
GetRsvp返回循環變量的地址,而不是數組中元素的地址。修理:
for i, element := range e.Rsvps {
if element.UserId == userId {
return &e.Rsvps[i], nil
}
}
循環變量保留 e.Rsvps[i] 的副本,并且它在每次迭代時都會被覆蓋。如果返回循環變量的地址,則返回該副本的地址。

TA貢獻1780條經驗 獲得超4個贊
當范圍覆蓋切片時,每次迭代都會返回兩個值。第一個是索引,第二個是該索引處元素的副本。
因此從技術上講,您正在嘗試修改 Rsvp 的副本。相反,從 GetRsvp() 方法返回索引并更新。
func (e *Event) GetRsvp(userId string) (int, error) {
for index , element := range e.Rsvps {
if element.UserId == userId {
return index, nil
}
}
return -1 , fmt.Errorf("could not find RSVP based on UserID")
}
func (e *Event) UpdateExistingRsvp(userId string, rsvpString string) {
index, err := e.GetRsvp(userId)
if err != nil || index == -1 {
fmt.Println("no such user")
}
e.Rsvps[index].RsvpString = rsvpString
}
- 2 回答
- 0 關注
- 140 瀏覽
添加回答
舉報