This question already has answers here:
My object is not updated even if I use the pointer to a type to update it

(3个答案)


2年前关闭。




这是我试图理解和更改的golang行为:我编写了一种在Golang中用 slice 填充结构的方法。它在方法本身内起作用,但是 slice 内容在方法外丢失。但是,我想保留内容。这可能是由于 slice 内部的指针在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

最佳答案

该方法必须在结构的指针“上”,如下所示:

func (self *mystruct) Foo () {}

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

关于pointers - slice 内容在函数调用后被删除,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53972388/

10-13 04:49
查看更多