satoru
satoru

Reputation: 33215

Why don't Go slices just switch the underlying array on reallocation?

A slice contains three components: length, capacity and a pointer to the underlying array.

When we try to append to a slice that is full (len(s) == cap(s)), a larger array will be allocated.

I read in a book that we have to assign the return value of append back to the slice, because a different slice may be returned due to reallocation of the underlying array.

runes = append(runes, r)

But I don't know why this is necessary. Can't we just reallocate a new array and update the pointer of the original slice instance?

Upvotes: 2

Views: 117

Answers (1)

Thundercat
Thundercat

Reputation: 120941

All function arguments are passed by value in Go. A function cannot change the caller's value.

The slice (length, capacity, pointer) is passed by value to the append function. Because append cannot change the caller's slice, the append function returns the new slice.

The append function could be written to take a pointer to a slice, but that would make append awkward to use in the many situations where slice values are not addressable.

Upvotes: 1

Related Questions