0
0
Goprogramming~5 mins

Accessing array elements in Go - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is an array in Go?
An array in Go is a fixed-size collection of elements of the same type, stored in contiguous memory locations.
Click to reveal answer
beginner
How do you access the first element of an array named arr in Go?
You access it using arr[0] because Go arrays are zero-indexed, meaning the first element is at index 0.
Click to reveal answer
intermediate
What happens if you try to access an array element with an index out of range in Go?
Go will cause a runtime panic with an 'index out of range' error, stopping the program.
Click to reveal answer
beginner
Given var arr = [3]int{10, 20, 30}, what is the value of arr[2]?
The value is 30, because array indices start at 0, so arr[2] is the third element.
Click to reveal answer
beginner
Can you change the value of an element in a Go array after it is created?
Yes, you can assign a new value to an element by accessing it with its index, like arr[1] = 50.
Click to reveal answer
What is the index of the first element in a Go array?
A1
B0
C-1
DDepends on the array size
How do you access the third element of an array named nums?
Anums[2]
Bnums[3]
Cnums[1]
Dnums[0]
What happens if you try to access arr[5] in an array of length 3?
ACompiles but undefined behavior
BReturns zero value
CReturns last element
DRuntime panic: index out of range
Can you assign a new value to an existing element in a Go array?
AYes, by using its index
BNo, arrays are immutable
COnly if the array is a slice
DOnly during array declaration
Which of these is a valid way to declare an array of 4 integers in Go?
Aarr := [4]int{1,2,3}
Bvar arr []int
Cvar arr [4]int
Darr := []int{1,2,3,4}
Explain how to access and modify elements in a Go array.
Think about how you get and set values using the index.
You got /4 concepts.
    Describe what happens if you try to access an array element outside its range in Go.
    What does Go do to protect you from invalid access?
    You got /4 concepts.