Home >Backend Development >Golang >Why Doesn't Appending to a Struct Slice Work in Go When Called From Another Method?

Why Doesn't Appending to a Struct Slice Work in Go When Called From Another Method?

Linda Hamilton
Linda HamiltonOriginal
2024-12-19 13:08:14221browse

Why Doesn't Appending to a Struct Slice Work in Go When Called From Another Method?

Cannot Append to Struct Slice Outside of Method

When working with slices in Go, a common issue arises when appending to a slice that is a property of a struct. In certain scenarios, this operation may fail despite working correctly when performed directly on the struct.

Consider the following example:

type Test1 struct {
  all []int
}

func (c Test1) run() []int {
  for i := 0; i < 2; i++ {
    c.all = append(c.all, i)
  }
  return c.all
}

Here, the code successfully appends to the all slice within the run method of the Test1 struct. However, if this method calls another method, the append operation fails.

For example:

type Test3 struct {
  all []int
}

func (c Test3) run() []int {
  c.combo()
  return c.all
}

func (c Test3) combo() {
  for i := 0; i < 2; i++ {
    c.all = append(c.all, i)
  }
}

In this scenario, the Test3.combo method attempts to append to the all slice but fails. The reason for this is that Go passes values by value, meaning a copy of the Test3 struct is created when c.combo() is called.

The copy operates on its own slice, and when the method returns, the associated changes are discarded. Therefore, when Test3.run tries to return c.all, it returns an empty slice because the copy's modified version is lost.

The solution to this issue is to use a pointer receiver for the combo method:

func (c *Test3) combo() {
  for i := 0; i < 2; i++ {
    c.all = append(c.all, i)
  }
}

Using a pointer receiver ensures that the method operates on the original Test3 struct, allowing changes made within the combo method to be preserved when it returns.

The above is the detailed content of Why Doesn't Appending to a Struct Slice Work in Go When Called From Another Method?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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