Defining golang struct function using pointer or not

前端 未结 4 1944
青春惊慌失措
青春惊慌失措 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:35

    As mentioned in the FAQ

    Should I define methods on values or pointers?

    func (s *MyStruct) pointerMethod() { } // method on pointer
    func (s MyStruct)  valueMethod()   { } // method on value
    

    First, and most important, does the method need to modify the receiver? If it does, the receiver must be a pointer. (Slices and maps act as references, so their story is a little more subtle, but for instance to change the length of a slice in a method the receiver must still be a pointer.)

    In the examples above, if pointerMethod modifies the fields of s, the caller will see those changes, but valueMethod is called with a copy of the caller's argument (that's the definition of passing a value), so changes it makes will be invisible to the caller.

    In your case, func (s Sample) Append(name string) modifies a copy.

    laher reminds us in the comments that using a value instead of pointer also means getting a copy, and respecting the immutable nature of an object::

    You'd want to use the non-pointer valueMethod when (for nstance) you're returning a [value derived from an] 'immutable' private property.

    See "Why are receivers pass by value in Go?":

    Can be useful if for instance you have a small immutable object. The caller can know for certain that this method doesn't modify it's receiver.
    They can't know this if the receiver is a pointer without reading the code first.

提交回复
热议问题