dourang20110122 2017-10-17 11:27
浏览 140
已采纳

Golang:调用将项添加到数组的方法后,数组为空[重复]

I am new to Golang. I have this simple code, that I can't get to work; the problem is that after call the method LoadGroups, the "main" function doesn't see the changes:

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-

</div>

展开全部

  • 写回答

2条回答 默认 最新

  • dongyong6428 2017-10-17 11:35
    关注

    You are modifying a copy of the Configuration, not the Configuration itself.

    The method LoadGroups should take a pointer to a Configuration instead:

    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()
    }
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部