GO Tutorial



ARRAYS IN GO


Arrays in Go

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.

Declaring Arrays

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.

Initializing Arrays

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}
  

Accessing Array Elements

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.

Modifying Array Elements

You can change the value at a particular index by assignment:

arr[1] = 42  // Changes the second element
  

Length of an Array

Use the built-in len() function to get the number of elements:

fmt.Println(len(arr))  // Prints the array length
  

Looping Through Arrays

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)
}
  

Important Notes

  • Arrays are value types in Go. Assigning one array to another copies all elements.
  • Since arrays have fixed size, for dynamic collections, use slices (covered in a separate tutorial).
  • Zero values: Numeric arrays initialize elements with 0, strings with "", booleans with false.
Summary: Arrays in Go are simple fixed-size collections of elements. They are suitable when the number of elements is known and fixed. For flexibility, slices are preferred.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review