In Go, an array is a data structure used to store multiple values of the
same type in a single variable. Instead of creating separate variables for
each value, arrays allow you to manage collections of data efficiently.
What Is an Array?
An array:
Holds a fixed number of elements
Stores elements of the same data type
Uses index-based access (starting from 0)
Important: The size of an array in Go is fixed once
declared and cannot be changed.
Declaring Arrays in Go
There are two common ways to declare arrays:
1. Using var
var scores = [4]int{85, 90, 78, 92}
2. Using Short Declaration (:=)
marks := [3]int{70, 80, 95}
Letting Go Infer Array Length
You can allow the compiler to determine the array size using
....
Working with Arrays
Example: Declaring and Printing Arrays
Accessing Array Elements
Array elements are accessed using their index.
Modifying Array Elements
You can update elements by assigning a new value to a specific index.
Array Initialization and Default Values
If elements are not initialized, Go assigns default values:
int → 0
string → ""
bool → false
Initializing Specific Elements
You can initialize selected indices directly.
Explanation:
Index 0 → 10
Index 3 → 40
Other elements default to 0
Finding the Length of an Array
Use the built-in len() function to get the number of elements.