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,
}
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.