Sobes.tech
Junior — Middle

Is it possible to perform a loop over an array or list that was declared without specifying parameters?

sobes.tech AI

Answer from AI

In Go, arrays and slices have a strictly defined type, including the element type and length (for arrays). If an array is declared without specifying the length, for example var arr []int, then it is a slice, not an array. You can perform a for range loop over a slice without issues.

However, if an array is declared without specifying the length, for example arr := [...]int{1,2,3}, the length is inferred by the compiler, and you can iterate over it as well.

But, if an array is declared without any parameters at all, for example var arr [], this is syntactically incorrect in Go — the type must be fully specified.

Example of a correct loop over a slice:

arr := []int{1, 2, 3}
for i, v := range arr {
    fmt.Println(i, v)
}

Thus, you can perform a loop over an array or slice if the type and length (for arrays) are known. Declaring without parameters is impossible.

Is it possible to perform a loop over an array or… - sobes.tech