dsk920417 2014-11-18 16:10
浏览 23
已采纳

从另一个函数追加到数组?

I have this code in which I am appending to an array of a struct in one function. The change does not appear in the other function.

type my struct{
arr []int
}

func New_my() *my {
  m := new (my)
  return m
}

func (m my) Dosomething(){
  m.arr = append(m.arr,1)
  m.arr = append(m.arr,2)
  m.arr = append(m.arr,3)
}

func (m my) Dosomethingelse(){
  fmt.Println(m.arr)
}

func main(){

  m:= New_my()
  m.Dosomething()
  m.Dosomethingelse()
}

The output is:

[]

Please, explain what is happening? Why does the change not appear in the array?

  • 写回答

2条回答 默认 最新

  • doutong2132 2014-11-18 16:14
    关注

    If you are new to go you should totally do the tour of go and the effective go document. Go is a new language and with a strange combination of ideas so the official documentation is the best place to start.

    First of all you are using a slice not an array. (Read this to understand slices)

    The error in your code is because Dosomething() is defined for my instead of *my. This is explained here.

    Just change it to:

    func (m *my) Dosomething(){
      m.arr = append(m.arr,1)
      m.arr = append(m.arr,2)
      m.arr = append(m.arr,3)
    }
    

    In go everything is passed by value so in your code you are passing a copy of the struct to the function Dosomething(), and because the capacity of the slice is 0, the append function creates a new underlying array and returns a reference to it, and when yo do:

    m.arr = append(...)
    

    the new slice (using the new array) is lost because it is stored in m that is a copy of the original struct, if m were a *my the new slice would replace the previous in the arr property.

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

报告相同问题?

悬赏问题

  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。