Sobes.tech
Junior — Middle

Is it possible to use a loop to traverse nil slice elements?

sobes.tech AI

Answer from AI

Yes, in Go, you can use a loop to iterate over a nil slice. The loop simply won't execute because the length of a nil slice is zero.

Example:

var s []int // nil slice
for i, v := range s {
    fmt.Println(i, v) // This code will not execute
}

Thus, iterating over a nil slice is safe and does not cause errors, which simplifies working with slices without the need for additional nil checks.

Is it possible to use a loop to traverse nil slice… - sobes.tech