如何修复:Golang“追加”方法将相同元素推送到切片

我正在尝试将数据从 DB ( Mongo ) 映射到 go 中的切片,如果我返回简单,则一切正常,[]string但如果我将类型更改[]*models.Organization为该代码,则会返回相同元素的切片。


func (os *OrganizationService) GetAll() ([]*models.Organization, error) {

    var organizations []*models.Organization

    results := os.MongoClient.Collection("organizations").Find(bson.M{})

    organization := &models.Organization{}

    for results.Next(organization) {

        fmt.Println(organization)

        organizations = append(organizations, organization)

    }

    return organizations, nil

}



我期望输出[{ Name: "someOrg", ID: "someId" },{ Name: "someOrg2", ID: "someID }, ... ],但实际输出是 [{ Name: "someOrg", ID: "someId" },{ Name: "someOrg", ID: "someId" }, ... ]


我正在使用bongo包。


海绵宝宝撒
浏览 124回答 1
1回答

泛舟湖上清波郎朗

organization应用程序在循环的每次迭代中附加相同的值。通过在循环内创建新值来修复。func (os *OrganizationService) GetAll() ([]*models.Organization, error) {    var organizations []*models.Organization    results := os.MongoClient.Collection("organizations").Find(bson.M{})    organization := &models.Organization{}    for results.Next(organization) {        fmt.Println(organization)        organizations = append(organizations, organization)        organization = &models.Organization{} // new value for next iteration    }    return organizations, nil}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go