Why Does Using a Value Receiver Lead to Incorrect Slice Modification in a Go Struct?

Patricia Arquette
Release: 2024-11-17 05:03:03
Original
978 people have browsed it

Why Does Using a Value Receiver Lead to Incorrect Slice Modification in a Go Struct?

Removing Elements from a Slice in a Struct (Resolved)

In the code snippet provided, there is an issue when attempting to remove an element from a slice within a struct using a value receiver. This leads to the incorrect modification of the slice in the original struct.

To resolve this, a pointer receiver must be used in the method that modifies the slice. This is because Go value receivers create a copy of the receiver value, which means any changes made to the receiver in the method are not reflected in the original struct.

Here is the corrected code:

func (guest *Guest) removeFriend(id int) {
    for i, other := range guest.friends {
        if other == id {
            guest.friends = append(guest.friends[:i], guest.friends[i+1:]...)
            break
        }
    }
}
Copy after login

By using a pointer receiver (*Guest), the method modifies the original Guest struct's friends slice, ensuring that the element is removed correctly.

Explanation:

When a slice is passed by value, the receiver method operates on a copy of the slice. When modifications are made to the slice, they are only reflected in the copy, not in the original slice. However, using a pointer receiver allows the method to modify the original slice, as the receiver is now a pointer to the original struct.

Example Usage:

guest := &Guest{
    id:      1,
    name:    "Bob",
    surname: "Pats",
    friends: []int{1, 2, 3, 4, 5},
}

fmt.Println(guest)
guest.removeFriend(3)
fmt.Println(guest)
Copy after login

Output:

&{1 Bob Pats [1 2 3 4 5]}
&{1 Bob Pats [1 2 4 5]}
Copy after login

The above is the detailed content of Why Does Using a Value Receiver Lead to Incorrect Slice Modification in a Go Struct?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template