首页 > 解决方案 > 函数调用后切片内容被删除

问题描述

这是我试图理解和改变的 golang 行为:我编写了一个方法来用 Golang 中的切片填充结构。它在方法本身内工作,但切片内容在方法之外丢失。但是我想保留内容。这可能来自切片内的指针在 populateslice 方法末尾被删除的事实,但我应该如何编写它以防止这种情况发生,即。在函数调用后保留 mystruct.myslice 中的内容?

这是我编写代码的方式:

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

标签: pointersgoappendslice

解决方案


该方法需要“打开”结构的指针,如下所示:

func (self *mystruct) Foo () {}

否则,您调用该方法的 mystruct 对象仅对该函数是本地的。


推荐阅读