Go Arrays: A Fixed-Size Collection
Arrays in Go provide a way to store multiple values of the same data type in a single variable. Unlike some other languages, Go arrays have a fixed size, meaning their length cannot be changed after creation.
Declaring and Initializing Arrays
There are two primary ways to declare an array in Go:
Using the var Keyword
Syntax
var arrayName [length]dataType
Explanation:
arrayName
: The name of the array.length
: The number of elements the array can hold.dataType
: The data type of the elements in the array.
Example:
Code Snippet
var numbers [5]int // An array of 5 integers
Output
None
You can also initialize an array during declaration:
Code Snippet
var fruits [3]string = ["apple", "banana", "orange"]
Output
None
Using Short Declaration (:=)
Syntax
arrayName := [length]dataType{values}
Explanation:
arrayName
: The name of the array.length
: The number of elements the array can hold.dataType
: The data type of the elements in the array.values
: Optional list of initial values.
Example:
Code Snippet
colors := [4]string{"red", "green", "blue", "yellow"}
Output
None
Array Length and Accessing Elements
Array Length
Use the len()
function to get the number of elements in an array.
Code Snippet
length := len(numbers)
Output
None
Accessing Elements
Use an index (starting from 0) to access individual elements.
Code Snippet
firstElement := numbers[0]
Output
None
Modifying Array Elements
You can change the value of an element by assigning a new value to its index:
Code Snippet
numbers[2] = 15
Output
None
Iterating Over Arrays
Use a for loop to iterate through all elements of an array:
Code Snippet
for i := 0; i < len(numbers); i++ {
fmt.Println(numbers[i])
}
Output
None
Key Points to Remember
- Arrays have a fixed size.
- Array elements are accessed using indices starting from 0.
- Arrays are value types, meaning assigning an array to another variable creates a copy.