Why `for k := range (*[3]int)(nil)` can compile pass


Why does this code compile and run successfully?

But,

func main() {
	p := (*[]int)(nil)
	for k := range p {
		fmt.Println(k)
	}
}

This code will compile error. Err is Cannot range over 'p' (type *[]int).

Isn’t for range in Go language not capable of range pointers?

Shouldn’t p in the first picture be a pointer?

Hi @ZonzeeLi , welcome to the forum.

Arrays and slices have a different internal structure. Especially, a slice has a header struct that contains a pointer that points to an underlying array, whereas an array is, well, just that.

The range operator cannot iterate over a pointer to a struct, but it can iterate over a pointer to an array.

To make the slice variant compile, dereference the pointer:

for k := range *p

Playground link (which also shows a more Go-ish way of initializing a pointer to a slice.)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.