0
0
Goprogramming~5 mins

Iterating over arrays in Go - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the basic way to loop over an array in Go?
Use the for loop with range to get index and value for each element in the array.
Click to reveal answer
beginner
What does the range keyword return when used with an array?
It returns two values: the current index and the value at that index in the array.
Click to reveal answer
beginner
How can you ignore the index when iterating over an array in Go?
Use an underscore _ in place of the index variable to ignore it, like for _, value := range arr.
Click to reveal answer
intermediate
Can you modify array elements while iterating with range in Go?
No, the value returned by range is a copy. To modify elements, use the index to access the array directly.
Click to reveal answer
beginner
Write a simple Go code snippet to print all elements of an array of integers.
```go
package main

import "fmt"

func main() {
    arr := [3]int{10, 20, 30}
    for i, v := range arr {
        fmt.Printf("Index %d: Value %d\n", i, v)
    }
}
```
Click to reveal answer
What does the range keyword return when used on an array in Go?
AOnly the index of each element
BOnly the value of each element
CIndex and value of each element
DThe entire array
How do you ignore the index when using range to iterate over an array?
AUse <code>_</code> instead of the index variable
BUse <code>nil</code> instead of the index variable
CUse <code>0</code> instead of the index variable
DYou cannot ignore the index
Can you change the elements of an array by modifying the value variable inside a range loop?
ANo, because the value is a copy
BYes, it changes the original array
COnly if the array is a slice
DOnly if you use pointers
Which of these is the correct syntax to iterate over an array arr in Go?
Afor (i, v) in arr {}
Bfor i in arr {}
Cforeach arr as i, v {}
Dfor i, v := range arr {}
What happens if you omit the index variable in a range loop like for v := range arr?
AIt will iterate only over the values
BIt will cause a compile error
CIt will iterate only over the indexes
DIt will iterate over both index and value
Explain how to use a for range loop to iterate over an array in Go and print each element.
Think about how you get both index and value from the array.
You got /4 concepts.
    Describe why modifying the value variable inside a range loop does not change the original array elements.
    Consider how Go handles values when iterating.
    You got /3 concepts.