Hopefully this is a quick question. So I was playing with Go and was reminded that passing a slice to a function doesn’t copy the slice to the function but ‘sortof’ passes it ByRef. You can mutate the slice without issue, but you cannot append(EDIT: unless you return the slice). I made the decision (mistake?) to ask chatgpt about it and it said that slices are special types that look like:
type slice struct {
ptr *T
len int
cap int
}
As I understand it, you’re then copying this ‘header’ to the function, so as long as the bounds don’t change it will work. but ‘append’ wont because it requires modifying this ‘header’.
chatgpt only told me about this invisible ‘type header’, and I inferred the rest. Is any of this correct?
Not quite. You can mutate the underlying array (ptr *T) that the slice points to. The slice doesn’t change. The data at the address it points to changes. Does that make sense?
This creates an array numbers which contains two numbers. Say this data lives at address 50. This also makes a slice/pointer to numbers.
slice[0] *= 2 will find the array the slice points to (address 50 + offset) and change the array data.
numbers[1] *= 2 does the same thing. Update the data at address 50 + offset.
Neither operation changes the slice data at all. It still points to the array at address 50. The contents of that array change but the slice data itself doesn’t change.