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

How to Correctly Append to a Slice within a Go Struct?

Susan Sarandon
Susan SarandonOriginal
2024-12-13 01:29:14269browse

How to Correctly Append to a Slice within a Go Struct?

Go - Appending to a Slice in a Struct

In Go, appending to a slice within a struct requires careful attention to variable references. This can become confusing when working with slices within structs, especially when the method receiving the struct is a pointer receiver.

Problem

Consider the following code:

package main

import "fmt"

type MyBoxItem struct {
    Name string
}

type MyBox struct {
    Items []MyBoxItem
}

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

func main() {
    item1 := MyBoxItem{Name: "Test Item 1"}
    box := MyBox{[]MyBoxItem{}} // Initialize box with an empty slice

    AddItem(box, item1)  // This is where the problem arises

    fmt.Println(len(box.Items))
}

The issue arises in the call to the AddItem method. When calling the method as AddItem(box, item1), instead of box.AddItem(item1), a new copy of the box struct is created rather than modifying the original.

Solution

To resolve this, assign the result of the AddItem method back to the original slice in the struct:

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

By doing this, the changes made to the slice within the AddItem method are reflected in the original slice field of the struct.

Revised Main Function

With the updated AddItem method, the corrected main function should be:

func main() {
    item1 := MyBoxItem{Name: "Test Item 1"}
    box := MyBox{[]MyBoxItem{}}

    box.AddItem(item1)  // Call the method correctly

    fmt.Println(len(box.Items))
}

Now, the output will correctly print the length of the Items slice, which should be 1 after adding the item.

The above is the detailed content of How to Correctly Append to a Slice within a Go 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