【发布时间】:2026-01-13 04:30:01
【问题描述】:
这是我试图理解和改变的 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
【问题讨论】: