我正在努力使我的 Go 應用程序更加面向對象?,F在我有以下電話: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 []Groupgroups.AllGroups.GrowGroupsArray()func (g Groups) GrowGroupsArray() { newSlice := make([]Group, len(g), 2*cap(g)+1) copy(newSlice, g) g.AllGroups = newSlice}這編譯得很好,但我得到了運行時恐慌,因為當函數完成時(超出范圍)沒有任何東西被保存到對象中。我在第一個示例工作但第二個不會將新數組保存到我的對象的幾個地方遇到了完全相同的問題。調用函數后,舊數組仍然存在。任何幫助將不勝感激。
1 回答

慕田峪9158850
TA貢獻1794條經驗 獲得超7個贊
我只需要這樣做:
//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
}
- 1 回答
- 0 關注
- 220 瀏覽
添加回答
舉報
0/150
提交
取消