Golang cannot range over pointer

I keep getting this error when trying to range over a slice pointer.

app/domain/repositories/class_repository.go:24: cannot range over classes (type *[]entities.Class)

What am I doing wrong?

You’re assuming the pointer to a slice will be automatically dereferenced for the iteration.

That’s not the case and there’s no reason for that because a slice is already a kind of pointer, rendering a pointer to a slice totally useless.

From Effective Go :

If a function takes a slice argument, changes it makes to the elements of the slice will be visible to the caller, analogous to passing a pointer to the underlying array.

Internally, a slice is made of

  • a pointer to the first element of the slice in the underlying array
  • the length of the slice
  • the capacity of the slice (the slice can usually be extended until the end of the array)

This structure is very small, rendering a pointer useless.