Home >Backend Development >Golang >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 }
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))
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 }
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!