I've never worked with C/C++, so I'm a bit stuck with pointers in go. The problem is: I have a map[string][]InteractiveItems
for each "room" and I wanna change slice of it in a function. Here it is:
func (r *room) getItem(arg string) InteractiveItem {
for i, val := range r.interactiveItems {
for _, item := range val {
if item.getName() == arg {
var idxToDelete int
for idx := range val {
if val[idx].getName() == arg {
idxToDelete = idx
break
}
if len(val) == 0 {
delete(r.interactiveItems, i)
}
}
val = append(val[:idxToDelete], val[idxToDelete+1:]...)
return item
}
}
}
return nil
Obviously, val
is changing inside the function, but room's map is not. How should I deal with pointers to delete the element of a slice?
This is because everything in Go is passed by value.
What this means for your case is that when you are iterating over the map, on each iteration the val
variable is assigned a copy of the corresponding slice value. So re-slicing the val
value inside the loop has no effect on the original slice inside the map, since one is a copy of, not a reference to, the other.
To change the slice that's inside the map you can re-assign the result of the append
operation to the corresponding map key.
r.interactiveItems[i] = append(val[:idxToDelete], val[idxToDelete+1:]...)
Keep in mind that when a slice is copied it does not copy the data that the slice points to, it copies only the slice's "descriptor".