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

huangapple go评论80阅读模式
英文:

How to make nested object oriented function calls in 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的类型是Groups
// AllGroups的类型是[]Group
groups.AllGroups.GrowGroupsArray()

func (g Groups) GrowGroupsArray() {
    newSlice := make([]Group, len(g), 2*cap(g)+1)
    copy(newSlice, g)
    g.AllGroups = newSlice
}

这样编译是没有问题的,但是当函数完成时(超出作用域),我会遇到运行时恐慌,因为没有将任何内容保存到对象中。我在几个地方遇到了完全相同的问题,第一个示例可以工作,但第二个示例无法将新数组保存到我的对象中。在函数调用后,旧数组仍然存在。任何帮助将不胜感激。

英文:

I'm trying to make my Go application more object oriented. Right now I have the following call:

groups.AllGroups = GrowGroupsArray(groups.AllGroups)

Which calls:

func GrowGroupsArray(g []Group) []Group {
    newSlice := make([]Group, len(g), 2*cap(g)+1)
    copy(newSlice, g)
    g = newSlice
    return g
}

This technically works but I would rather this:

//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
}

This compiles fine but I get a runtime panic because nothing is being saved to the object when the function is completed (out of scope). I've encountered the exact same issue in several places where the first example works but the second will not save the new array to my object. The old array persists after the function has been called. Any help would be greatly appreciated.

答案1

得分: -1

我只需要做这个:

// groups 是 Groups 类型
// AllGroups 是 []Group 类型
groups.AllGroups.GrowGroupsArray()

func (g *Groups) GrowGroupsArray() { //<- 将其改为指针方法
    newSlice := make([]Group, len(g), 2*cap(g)+1)
    copy(newSlice, g)
    g.AllGroups = newSlice
}
英文:

I just needed to do this:

//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
}

huangapple
  • 本文由 发表于 2016年1月23日 03:51:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/34954793.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定