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

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

DDD
Release: 2024-12-16 11:36:18
Original
797 people have browsed it

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

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

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template