dongshi9526 2016-07-01 01:01
浏览 18

函数返回后,在数组的struct成员上设置的值丢失

In golang, my understanding was that array slice types are references. I've got a problem where golang is acting like it is making copies of the data, rather than passing references around.

https://play.golang.org/p/EfEOMV_wcS

type Temp struct {
    Id   string `json:"id"`
    Lost string `json:"lost"`
}

func makeFoo1() []Temp {
    foos := make([]Temp, 0)
    foos = append(foos, Temp{Id: "foo"})
    return foos
}

func makeFoo2() []Temp {
    foos := makeFoo1()
    for _, t := range foos {
        t.Lost = "lost"
    }
    return foos

}

func main() {
    j, _ := json.Marshal(makeFoo2())
    fmt.Printf("%s
", j)
}

The output of this is [{"id":"foo","lost":""}]

How can the assignment t.Lost = "..." be made in makeFoo2 so it doesn't get lost? Or I guess the real question is how do I ensure the array is a reference and not a value?

  • 写回答

1条回答 默认 最新

  • douchi1945 2016-07-01 01:10
    关注

    I figured this out myself - what range returns is actually a copy. This fixed it

    func makeFoo2() []Temp {
        foos := makeFoo1()
        for i, _ := range foos {
            foos[i].Lost = "lost"
    
        }
        return foos
    
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助