Junior
What happens if you substitute a variable into an array?
sobes.tech AI
Answer from AI
package main
import "fmt"
func main() {
var value int = 10
// Assigning a variable's value to an array element
arr := [3]int{1, 2, 3}
arr[1] = value // The value 10 is assigned to arr[1]
fmt.Println(arr)
// Using a variable as an array index
var index int = 0
fmt.Println(arr[index]) // Will output the value of arr[0]
// Using a variable in an expression during array initialization (not possible for size)
// size := 5
// arr2 := [size]int{} // Error: array size must be a compile-time constant
// Using a variable to initialize elements
arr3 := [2]int{value, 5} // arr3 will be {10, 5}
fmt.Println(arr3)
}
In Golang, a variable can be used in the following ways in the context of arrays:
- Assigning a variable's value to an array element: The variable can hold a value that is then assigned to a specific array element by its index.
- Using a variable as an array index: The variable can contain an integer value used to access an array element by index. It is important that the variable's value is within the valid index range of the array (from 0 to
array length- 1), otherwise a runtime panic with "index out of range" error will occur. - Using a variable during array element initialization: The variable can be used in an expression to set the initial value of an array element during its declaration.
It is important to note that the array size in Golang must be a compile-time constant. A variable cannot be used to determine the size of an array during its declaration.