Golang Slice Help (for a C guy)
I’m trying to get better with Go slices, and I’m having trouble building the right mental model.
When I learn a new language, I usually implement a deck of cards to practice things like traversal, initialization, and shuffling. Right now I’m implementing Fisher-Yates shuffle.
In C, I would write something like this:
void shuffle(int *array, int n) {
if (n > 1) {
srand(time(NULL));
for (int i = n - 1; i > 0; i--) {
// Pick a random index from 0 to i
int j = rand() % (i + 1);
//Swap array[i] with array[j]
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
This makes sense to me because I can clearly see the temporary variable and the swap.
Now Go's turn
func (d *Deck) Shuffle() {
for i := len(d.Cards) - 1; i > 0; i-- {
j := rand.IntN(i + 1)
d.Cards[i], d.Cards[j] = d.Cards[j], d.Cards[i]
}
}
The part that confuses me is this line:
d.Cards[i], d.Cards[j] = d.Cards[j], d.Cards[i]
I understand that d.Cards is a slice, and that assigning to d.Cards[i] mutates the underlying array. But I don’t understand how this swap works without a temporary variable?
Is Go evaluating the right-hand side first, then assigning both values to the left-hand side? if so is slices the only place golang evaluates right side expressions first?
Also, for people who came from C/C++/Java/C#, did Go slices feel strange at first? Did the mental model eventually click?