dongzhang6544 2017-02-05 23:09
浏览 31
已采纳

为什么我对数组中嵌套结构的更改在进行更改的函数之外丢失了?

I'm still in the "wrestling with the language" stage of my Go progress, so forgive me for almost definitely missing something very obvious here.

I'm defining two structs, one containing the other. I make an array of the outer structs, pass it to a function, which calls a method on each of the inner structs, modifying their contents. This change is visible within the function, but when adding the outer structs to an array for returning, the outer function can't see the changes. I've tried throwing pointers in everywhere to little avail - somewhat thankfully, because it looked awful.

package main

import "github.com/davecgh/go-spew/spew"

type inner struct {
  ints []int
}

func (i *inner) grow() {
  i.ints = append(i.ints, 0)
}

type outer struct {
  inner inner
}

func growOs(os []outer) (out []outer) {
  for _, o := range os {
    o.inner.grow()
    out = append(out, o)
  }
  spew.Dump("----------during")
  spew.Dump(out)
  return
}

func main() {
  os := []outer{
    outer{},
    outer{},
  }
  spew.Dump("----------pre")
  spew.Dump(os)
  growOs(os)
  spew.Dump("----------post")
  spew.Dump(os)
}
  • 写回答

3条回答 默认 最新

  • dongsi2317 2017-02-06 01:02
    关注

    You should change

    func main() {
        os := []outer{
            outer{},
            outer{},
        }
        spew.Dump("----------pre")
        spew.Dump(os)
        growOs(os)
        spew.Dump("----------post")
        spew.Dump(os)
    }
    

    to

    func main() {
        os := []outer{
            outer{},
            outer{},
        }
        spew.Dump("----------pre")
        spew.Dump(os)
        os = growOs(os)
        spew.Dump("----------post")
        spew.Dump(os)
    }
    

    NOTICE: os = growOs(os)

    in function

    func growOs(os []outer) (out []outer) {
      for _, o := range os {
        o.inner.grow()
        out = append(out, o)
      }
      spew.Dump("----------during")
      spew.Dump(out)
      return
    }
    

    you just return a new slice out, you don't modify the input slice os,

    So in your main function, the os isn't changed.

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

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了