Home >Backend Development >Golang >How to Modify a Slice Within a Struct in Go?

How to Modify a Slice Within a Struct in Go?

Susan Sarandon
Susan SarandonOriginal
2024-11-21 06:00:14450browse

How to Modify a Slice Within a Struct in Go?

How to Remove an Element from a Slice in a Struct

Removing an element from a slice within a struct requires addressing several key considerations.

Issue: Slice Length Remains Unchanged

In the provided code snippet, the removeFriend method aims to remove an element from the friends slice. However, the last element of the slice is duplicated instead of the slice becoming shorter. This occurs because the method uses a value receiver, modifying a copy of the struct rather than the original value.

Solution: Utilize a Pointer Receiver

To ensure that changes made within the method affect the original struct, a pointer receiver should be employed. This allows the method to modify the actual struct instance. The syntax for a pointer receiver in Go is func (receiver *struct_name).

Example:

type Guest struct {
    id      int
    name    string
    surname string
    friends []int
}

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

Explanation:

By utilizing a pointer receiver (*Guest), the removeFriend method now modifies the friends slice of the original Guest struct.

Idiomatic Receiver Naming

It's important to note that receiver names like self and this are not commonly used in Go. Instead, more specific names like g or guest are preferred to convey the intention of the method.

The above is the detailed content of How to Modify a Slice Within a Struct in Go?. 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