Home  >  Article  >  Backend Development  >  Why Do I Need a Pointer Receiver to Remove an Element from a Slice in a Struct?

Why Do I Need a Pointer Receiver to Remove an Element from a Slice in a Struct?

Barbara Streisand
Barbara StreisandOriginal
2024-11-17 11:29:02973browse

Why Do I Need a Pointer Receiver to Remove an Element from a Slice in a Struct?

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!

Statement:
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