Defining golang struct function using pointer or not

前端 未结 4 1945
青春惊慌失措
青春惊慌失措 2021-01-31 03:12

Can someone explain to me why appending to an array works when you do this:

func (s *Sample) Append(name string) {
    d := &Stuff{
        name: name,
    }         


        
4条回答
  •  花落未央
    2021-01-31 03:54

    Go passes arguments by value, not by reference, unless you use a pointer. So inside the function, you're not modifying s in any outer scope if you simply pass by value. However, when you pass a pointer, you're able to modify the "real" variable rather than just the copy that exists inside the function.

提交回复
热议问题