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

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?

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.

In Go everything is passed by value, including the this/self/me/m argument provided to receivers (aka methods).

In Go if something does not appear to be passed by value, then either a pointer to it, or a struct containing a pointer (as is the case for string, slice, etc) is being passed.

That means right now your DoSomething gets a copy of the self-object and appends to that.

So in this case Topo is correct, you just need to change DoSomething() to pass its self/this/m argument as a pointer.

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

I assume this is toy code, but a couple of notes:

You could write this more efficiently as:

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

And it would be more idiomatic to rename New_my() to newMy()