Defining golang struct function using pointer or not

前端 未结 4 1989
青春惊慌失措
青春惊慌失措 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条回答
  •  Happy的楠姐
    2021-01-31 03:37

    Go slices are a tricky beast. Internally, a variable of slice type (like []int) looks like this:

    struct {
        data *int // pointer to the data area
        len  int
        cap  int
    }
    

    When you pass a slice to a function, this structure is passed by value, while the underlying data area (i.e. what data points to) is not copied. The builtin append() function modifies the data area (or generates a new one) and returns a new slice with updated len, data, and cap values. If you want to overwrite anything that is not part of the underlying data area, you need to pass a pointer to the slice or return a modified slice.

提交回复
热议问题