Home > Backend Development > Golang > Why Doesn't Appending to a Slice in a Go Struct Work Without Reassignment?

Why Doesn't Appending to a Slice in a Go Struct Work Without Reassignment?

Susan Sarandon
Release: 2024-12-14 09:34:14
Original
421 people have browsed it

Why Doesn't Appending to a Slice in a Go Struct Work Without Reassignment?

Go - append to slice in struct

In Go, when trying to append to a slice within a struct, the most common mistake is failing to assign the result back to the slice.

Consider the following example:

type MyBoxItem struct {
    Name string
}

type MyBox struct {
    Items []MyBoxItem
}

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

The function AddItem takes a MyBoxItem and appends it to the Items slice of the MyBox struct. It returns the updated slice.

Now, the main function:

item1 := MyBoxItem{Name: "Test Item 1"}
item2 := MyBoxItem{Name: "Test Item 2"}

items := []MyBoxItem{}
box := MyBox{items}

AddItem(box, item1)  // Attempt to add item without fixing assignment

fmt.Println(len(box.Items))
Copy after login

This code attempts to call the AddItem method on the box struct and pass item1. However, it fails to assign the result back to the box.Items slice.

To fix this, the code should be modified as follows:

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

Also, since the AddItem function is defined for the *MyBox type, it should be called as box.AddItem(item1).

The above is the detailed content of Why Doesn't Appending to a Slice in a Go Struct Work Without Reassignment?. 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