An array is a collection of elements that have the same data type, arranged in a fixed-size sequence. Arrays in Go are fixed-length, meaning once declared, their size cannot be changed.
You declare an array by specifying its size and element type. Syntax:
var arr [5]int
This declares an integer array arr
with 5 elements, all initialized to zero by default.
You can initialize arrays while declaring:
var arr = [3]string{"Go", "Python", "Java"}
Or use shorthand declaration:
arr := [4]int{10, 20, 30, 40}
You can also let Go infer the array size by using ...
instead of a number:
arr := [...]float64{3.14, 2.71, 1.62}
Array elements are accessed using zero-based indices:
fmt.Println(arr[0]) // Prints first element fmt.Println(arr[2]) // Prints third element
Note: Accessing an index outside the array length will cause a compile-time error.
You can change the value at a particular index by assignment:
arr[1] = 42 // Changes the second element
Use the built-in len()
function to get the number of elements:
fmt.Println(len(arr)) // Prints the array length
You can use for
loops with range
to iterate over arrays easily:
for i, val := range arr { fmt.Printf("Index %d: %v\n", i, val) }
slices
(covered in a separate tutorial).0
, strings with ""
, booleans with false
.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!