Home >Backend Development >Golang >How to Correctly Append to a Slice within a Go Struct's Method?

How to Correctly Append to a Slice within a Go Struct's Method?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-12 21:27:11143browse

How to Correctly Append to a Slice within a Go Struct's Method?

Append to Slice in Go Struct

In this code snippet, the user attempts to implement two structs: MyBoxItem and MyBox. The intention is to add an item to the MyBox struct using the AddItem method. However, the current implementation isn't working.

The problem lies in the AddItem method:

func (box *MyBox) AddItem(item MyBoxItem) []MyBoxItem {
    return append(box.Items, item)
}

By default, the slice value is copied into the parameters by value, not by reference. As a result, any changes made to the parameter's slice will not be reflected in the original slice. To fix this, the original slice needs to be assigned the result of the append function.

func (box *MyBox) AddItem(item MyBoxItem) []MyBoxItem {
    box.Items = append(box.Items, item)
    return box.Items
}

Additionally, the AddItem method is defined for a pointer to MyBox type (*MyBox), so you should call it as box.AddItem(item1) in the main function.

The above is the detailed content of How to Correctly Append to a Slice within a Go Struct's Method?. 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