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
Release: 2024-12-13 01:29:14
Original
259 people have browsed it

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))
}
Copy after login

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)
}
Copy after login

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))
}
Copy after login

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!

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