Removing an Element from a Slice in a Struct
To remove an element from a slice in a struct, you must use a pointer receiver, rather than a value receiver. A value receiver modifies a copy of the original struct, while a pointer receiver modifies the original struct itself.
Code Example
Consider this code to remove a friend from a Guest struct:
type Guest struct { id int name string surname string friends []int } func (self Guest) removeFriend(id int) { for i, other := range self.friends { if other == id { self.friends = append(self.friends[:i], self.friends[i+1:]...) break } } }
This code will not work because it uses a value receiver, (self Guest). To modify the original struct, you must use a pointer receiver, (self Guest)*.
Correct Code
func (self *Guest) removeFriend(id int) { for i, other := range self.friends { if other == id { self.friends = append(self.friends[:i], self.friends[i+1:]...) break } } }
Now, calling guest1.removeFriend(3) will remove the friend with ID 3 from the guest1 struct.
Note:
Also note that using receiver names like (self) and (this) is not idiomatic in Go. Instead, use the name of the struct, such as (guest).
The above is the detailed content of Why Do I Need a Pointer Receiver to Remove an Element from a Slice in a Struct?. For more information, please follow other related articles on the PHP Chinese website!