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 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输