oop - 如何在 GO 中进行嵌套的面向对象的函数调用

标签 oop go

我正在努力使我的 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/

相关文章:

Java继承: How to declare a static variable in Super and instantiate it in subclass

python - 确保 Python 中不存在 __init__ 函数

go - 将所有错误处理的 golang 错误代码替换为 panic

unit-testing - 包含源和目标的 zip 文件夹

go - 将 slice/数组传递给另一个结构

java - 在android中创建类似glide和picasso的类结构

python - 多重继承 --> Fish.__init__() 缺少 2 个必需的位置参数

c++ - C++中如何限制对象私有(private)数据成员的修改?

http - 静态目录未得到服务

go - fmt 函数代表什么?