0
0
Goprogramming~10 mins

Array initialization in Go - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Array initialization
Declare array variable
Specify array size
Assign values to elements
Array ready to use
This flow shows how an array is declared with a fixed size and then each element is assigned a value before use.
Execution Sample
Go
package main

import "fmt"

func main() {
    var arr [3]int
    arr[0] = 10
    arr[1] = 20
    arr[2] = 30
    fmt.Println(arr)
}
This code declares an integer array of size 3, assigns values to each element, and prints the array.
Execution Table
StepActionArray StateOutput
1Declare array 'arr' of size 3 with default values[0 0 0]
2Assign arr[0] = 10[10 0 0]
3Assign arr[1] = 20[10 20 0]
4Assign arr[2] = 30[10 20 30]
5Print arr[10 20 30][10 20 30]
💡 All elements assigned, array printed, program ends.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
arr[0 0 0][10 0 0][10 20 0][10 20 30][10 20 30]
Key Moments - 3 Insights
Why does the array start with zeros before assignment?
In Go, arrays are initialized with zero values for their type automatically, as shown in step 1 of the execution_table.
Can we assign values beyond the declared size of the array?
No, the array size is fixed at declaration. Trying to assign beyond index 2 (for size 3) will cause a compile-time error.
What happens if we print the array before assigning any values?
The array will print with all zero values, as seen in step 1 where arr is [0 0 0].
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the array state after step 3?
A[10 20 0]
B[10 0 0]
C[0 0 0]
D[10 20 30]
💡 Hint
Check the 'Array State' column in row with Step 3 in execution_table.
At which step is the array printed?
AStep 2
BStep 4
CStep 5
DStep 1
💡 Hint
Look for the 'Print arr' action in execution_table.
If we remove the assignment at step 4, what would be the final array state?
A[10 20 30]
B[10 20 0]
C[0 0 0]
D[10 0 0]
💡 Hint
Refer to variable_tracker and see the effect of skipping step 4 assignment.
Concept Snapshot
Array initialization in Go:
- Declare with fixed size: var arr [3]int
- Elements start with zero values
- Assign values by index: arr[0] = 10
- Size cannot change after declaration
- Use fmt.Println(arr) to print entire array
Full Transcript
This example shows how to create an array in Go. First, we declare an array named arr with size 3. Go automatically fills it with zeros. Then, we assign values 10, 20, and 30 to each element by their index. Finally, we print the array, which outputs [10 20 30]. Arrays have fixed size, so you cannot add more elements than declared.