我正在努力使我的 Go 应用程序更加面向对象。现在我有以下电话:
groups.AllGroups = GrowGroupsArray(groups.AllGroups)
调用:
func GrowGroupsArray(g []Group) []Group {
newSlice := make([]Group, len(g), 2*cap(g)+1)
copy(newSlice, g)
g = newSlice
return g
}
这在技术上可行,但我更愿意这样:
//groups is of type Groups
//AllGroups is of type []Group
groups.AllGroups.GrowGroupsArray()
func (g Groups) GrowGroupsArray() {
newSlice := make([]Group, len(g), 2*cap(g)+1)
copy(newSlice, g)
g.AllGroups = newSlice
}
这编译得很好,但我得到了一个运行时 panic ,因为当函数完成时(超出范围)没有任何东西被保存到对象中。我在第一个示例工作的几个地方遇到了完全相同的问题,但第二个示例不会将新数组保存到我的对象中。调用函数后,旧数组仍然存在。任何帮助将不胜感激。
最佳答案
我只需要这样做:
//groups is of type Groups
//AllGroups is of type []Group
groups.AllGroups.GrowGroupsArray()
func (g *Groups) GrowGroupsArray() { //<- Make this a pointer method
newSlice := make([]Group, len(g), 2*cap(g)+1)
copy(newSlice, g)
g.AllGroups = newSlice
}
关于oop - 如何在 GO 中进行嵌套的面向对象的函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34954793/