Home >Backend Development >Golang >How to Remove Elements from a Slice Within a Struct in Go?
Removing Elements from a Slice Within a Struct
In Go, structs are aggregates of fields, which can include slices. When a method attempts to modify the receiver (i.e., the struct itself), it must use a pointer receiver to update the original value rather than creating a copy.
Consider the following code:
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 removes an element from the "friends" slice within the "Guest" struct. However, attempting to remove an element from the original struct results in overwriting the desired element and multiplying the last element, as seen in the example:
guest1.friends = [1, 2, 3, 4, 5] guest1.removeFriend(3) // Result: guest1.friends = [1, 2, 4, 5, 5]
To rectify this issue, you must use a pointer receiver:
func (self *Guest) removeFriend(id int) { // ... (Same implementation) }
By using a pointer receiver, you assign the new slice value (returned by "append()") to the "friends" field of the original "Guest" struct, effectively reducing the slice length by 1.
Additionally, it's recommended to use a more idiomatic receiver name, such as "guest" or "g," instead of "self."
The above is the detailed content of How to Remove Elements from a Slice Within a Struct in Go?. For more information, please follow other related articles on the PHP Chinese website!