I'm a bit confused as to why this happens when attempting to remove an element from a slice in Go.
As a simplified example, I have the following data structures:
type Person struct {
Name string
}
type People []Person
I want to add a method to remove a person with a certain name from the list of people with people.Remove("Sam")
:
func (p *People) Remove(name string) {
for i, person := range *p {
if person.Name == name {
// Doesn't work
*p = append(*p[:i], *p[i+1:]...)
}
}
}
I thought this would work, but referencing the slice elements in this manner returns a compile error: cannot slice p (type *People)
.
So, fair enough. But when I set *p
to another variable (a
), it works exactly as expected:
func (p *People) Remove(name string) {
for i, person := range *p {
if person.Name == name {
// Does work
a := *p
*p = append(a[:i], a[i+1:]...)
}
}
}
Why do I need to set the slice to a difference variable before this method works? Shouldn't the behaviour be exactly the same?
I'm probably misunderstanding something fundamental here so if anyone can explain why this is required I'd love to know. Thank you!