gpt4 book ai didi

pointers - 函数调用后删除的 slice 内容

转载 作者:数据小太阳 更新时间:2023-10-29 03:45:47 25 4
gpt4 key购买 nike

<分区>

这是我试图理解和改变的 golang 行为:我写了一个方法来在 Golang 中用 slice 填充结构。它在方法本身内工作,但 slice 内容在方法之外丢失。但是我想保留内容。这可能是因为在 populateslice 方法的末尾删除了 slice 内的指针,但我应该如何编写它以防止这种情况发生,即。在函数调用后保留 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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com