arrays - 戈朗 : array is empty after call a method that adds items to the array

标签 arrays go struct slice

<分区>

我是 Golang 的新手。我有这个简单的代码,我无法开始工作;问题是调用方法 LoadGroups 后,“main”函数看不到变化:

package main

import "fmt"

type Group struct {
    Name string
}

type Configuration struct {
    Groups []Group
}

func NewConfiguration() (error, *Configuration) {
    conf := Configuration{}
    conf.LoadGroups()
    fmt.Print("Final number of groups: ", len(conf.Groups))
    return nil, &conf
}

func (conf Configuration) LoadGroups() {
    for i := 0; i < 5; i++ {
        conf.Groups = append(conf.Groups, Group{Name: "Group " + string(i)})
        fmt.Println("Current number of groups: ", len(conf.Groups))
    }
}

func main() {
    NewConfiguration()
}

Playground :https://play.golang.org/p/VyneKpjdA-

最佳答案

您正在修改配置的副本,而不是配置本身。

LoadGroups 方法应该采用指向配置的指针:

package main

import "fmt"

type Group struct {
    Name string
}

type Configuration struct {
    Groups []Group
}

func NewConfiguration() (error, *Configuration) {
    conf := &Configuration{}
    conf.LoadGroups()
    fmt.Print("Final number of groups: ", len(conf.Groups))
    return nil, conf
}

func (conf *Configuration) LoadGroups() {
    for i := 0; i < 5; i++ {
        conf.Groups = append(conf.Groups, Group{Name: "Group " + string(i)})
        fmt.Println("Current number of groups: ", len(conf.Groups))
    }
}

func main() {
    NewConfiguration()
}

关于arrays - 戈朗 : array is empty after call a method that adds items to the array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46797776/

相关文章:

javascript - TypeError : $scope. array.reduce 不是一个函数

c++ - 数组遍历中的BST

go - 从单独的包函数返回的结构错误

swift - 从同一类中的结构调用方法

python - 如何将列表中的单词放入表格中?

C++ 将文本文件读入 vec4 数组

go - http.ServeFile 在服务器 golang 上返回 404 not found 错误

google-app-engine - 从已部署的应用连接到 Google Cloud SQL 服务器时遇到问题

c++ - 链接错误,怎么回事?

arrays - 保存和加载结构数组的最佳做法是什么?