Heim > Artikel > Backend-Entwicklung > Wie entferne ich Elemente aus einem Slice innerhalb einer Struktur 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."
Das obige ist der detaillierte Inhalt vonWie entferne ich Elemente aus einem Slice innerhalb einer Struktur in Go?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!