-4

here is a golang behavior that I am trying to understand and change: I wrote a method to populate a structure with slices in Golang. It works within the method itself, but the slice content gets lost outside of the method. I want however to keep the content. It probably comes from the fact that the pointers inside the slice where deleted at the end of the populateslice method, but how should I write it to prevent this to happen, ie. keep the content in mystruct.myslice after the function call ?

Here is how I wrote the code:

type BBDatacolumn struct {
  Data []string
}

type Mystruct struc {
   myslice []BBDatacolumn
}

//Method to populate the slice of the structure mystruct:
func (self mystruct) populateslice() {
   for i:=0; i<imax; i++ {
     bufferdatacolumn := NewBBDatacolumn()
     //Here, code to populate bufferdatacolumns

     self.myslice = append(self.myslice, bufferdatacolumn)
  }

  self.myslice.display() //Here, works fine: myslice contains the data of the BBDatacolumn correctly
}

//Later in the code (outside of the populateslice func):
mystructinstance.populateslice() //Populates slice OK at the end of the function
mystructinstance.display() //Problem: mystructinstance.myslice is empty: Instanciation of Mystruct does not contain the data in myslice anymore as it did inside the populateslice method
Emanolo78
  • 309
  • 5
  • 10

2 Answers2

1

The method needs to be "on" a pointer of your struct, like so:

func (self *mystruct) Foo () {}

Otherwise the mystruct object that you call the method on is local only to the function.

robert
  • 731
  • 1
  • 5
  • 22
1

In go the receiver of a method (the part between func and the method name) can either be a value receiver as you have or a pointer receiver. When you have a value receiver a copy of the object is passed to the method so any modifications made remain in that copy. If you want to modify the object then you must have a pointer receiver as so:

func (self *mystruct) populateslice() {

For a wider discussion of which is best in general see here:

Value receiver vs. Pointer receiver in Golang?

Iain Duncan
  • 3,139
  • 2
  • 17
  • 28