Situation:
I've learned about pointer receivers and value receivers. From what I understand: if you want to modify the object itself, you need to use a pointer receiver. I was reading more about interfaces in the go documentation and found this chunk of code:
type Sequence []int
// Methods required by sort.Interface.
func (s Sequence) Len() int {
return len(s)
}
func (s Sequence) Less(i, j int) bool {
return s[i] < s[j]
}
func (s Sequence) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
The Less
and Len
methods are using value receivers and this makes sense, because they are returning data and not modifying the Sequence
state.
But in the Swap
example, I am curious why it is still using a value receiver when it looks like it is trying to modify its state.
Question:
Is this a mistake, or is my understanding of value/pointer receivers flawed in some way?
To expand a bit on @squiguy's comment, the value of a slice object is itself a reference to an underlying array, including a pointer to the element in the array at which the slice begins, the length of the slice, and the slice's capacity (the number of elements in the underlying array from the beginning of the slice to the end of the array). When you pass a slice to a function, it is the above information that is passed by value, so the slice within the function still refers to the same underlying array. This is how Swap
is able to swap elements in the slice even though the slice itself is passed by value.