go / beginner
Snippet
Fixed-Size Arrays in Go
Arrays in Go have a fixed size determined at compile time. Unlike slices, arrays cannot grow or shrink. When declared with var, all elements are initialized to the zero value of the element type. You can also initialize arrays with values using the shorthand syntax. The len() function returns the array's length. The range keyword iterates over elements with both index and value.
snippet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package mainimport "fmt"func main() {var nums [5]int // Array of 5 integers, initialized to zeronums[0] = 10nums[1] = 20nums[2] = 30grades := [3]int{95, 87, 92} // Array with initial valuesfmt.Println("nums:", nums) // [10 20 30 0 0]fmt.Println("grades:", grades) // [95 87 92]fmt.Println("Length of nums:", len(nums))for i, v := range nums {fmt.Printf("nums[%d] = %d\n", i, v)}}
Breakdown
1
var nums [5]int
Declares an array of exactly 5 integers, all set to zero (0)
2
grades := [3]int{95, 87, 92}
Creates an array of 3 elements with specified values
3
len(nums)
Returns the fixed length of the array, which is 5
4
for i, v := range nums
Iterates through all elements, i is index, v is value