Go - Appending to a Slice Within a Struct
In Go, slices are reference types, meaning that they hold a reference to the underlying array. If you append an element to a slice within a struct and do not assign the result back to the slice, the changes will not be persisted when the function returns.
Consider the following code:
type MyBoxItem struct { Name string } type MyBox struct { Items []MyBoxItem } func (box *MyBox) AddItem(item MyBoxItem) []MyBoxItem { return append(box.Items, item) }
Here, the AddItem method takes an item and appends it to the slice of items in the box struct. However, the method does not assign the result back to the Items slice, which means that the slice will not be modified when the method returns.
To fix this, you need to assign the result of the append operation back to the slice. You can do this by modifying the AddItem method as follows:
func (box *MyBox) AddItem(item MyBoxItem) { box.Items = append(box.Items, item) }
Now, when you call the AddItem method, the slice will be updated within the struct. You can verify this by calling the len function on the Items slice:
item1 := MyBoxItem{Name: "Test Item 1"} item2 := MyBoxItem{Name: "Test Item 2"} items := []MyBoxItem{} box := MyBox{items} box.AddItem(item1) fmt.Println(len(box.Items)) // Output: 1
Note that the AddItem method is defined for the *MyBox type, which means that you must call it as box.AddItem(item1), passing a pointer to the box struct as an argument.
The above is the detailed content of Why Doesn't Appending to a Slice in a Go Struct Persist Without Reassignment?. For more information, please follow other related articles on the PHP Chinese website!