pointers - 函数调用后切片内容被删除
问题描述
这是我试图理解和改变的 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
解决方案
该方法需要“打开”结构的指针,如下所示:
func (self *mystruct) Foo () {}
否则,您调用该方法的 mystruct 对象仅对该函数是本地的。
推荐阅读
- jenkins - 矩阵管道卡住等待安排构建
- flutter - 打开卡片上的特定页面
- node.js - Node.js''跳过''一行代码??[截屏]
- stack - stack' 没有命名类型;您指的是 'obstack' 吗?我有一个 .h、cpp 和 main.cpp 文件。我得到这个错误
- python - 将 .html 文件从 Google Drive 发布到 WordPress
- pine-script - 如何使情节线默认在松脚本中不可见
- python - 在 Windows 上使用 Flask-SQLAlchemy create_all() 获取 AttributeError
- amazon-dynamodb - 调用资源“MyPhone223546421”时 Cloudformation 挂起
- ios - Swift MKMapItem 对象访问其私有成员
- ionic-framework - 将服务器中的 ionic 应用程序迁移为网站