Introduction to Arrays in Go
Arrays are a fundamental data structure in Go, allowing you to store a fixed-size sequence of elements of the same type. In this tutorial, we’ll explore arrays in Go, covering their declaration, initialization, manipulation, and practical usage with code examples.
What are Arrays?
An array in Go is a fixed-size sequence of elements of the same type. The size of an array is fixed at compile time and cannot be changed during the program’s execution.
Declaring Arrays
You can declare an array in Go using the following syntax:
var arrayName [size]dataType
Here’s an example:
var numbers [5]int
This declares an array named numbers
that can hold five integers.
Initializing Arrays
Arrays in Go can be initialized during declaration or later using literals. Here’s how you can initialize an array during declaration:
var numbers = [5]int{1, 2, 3, 4, 5}
Alternatively, you can let Go infer the size of the array:
numbers := [...]int{1, 2, 3, 4, 5}
Accessing Elements of an Array
You can access elements of an array using zero-based indexing. For example:
fmt.Println(numbers[0]) // Output: 1
Modifying Array Elements
Array elements can be modified directly by assigning new values to them:
numbers[0] = 10
Iterating Through Arrays
You can iterate through arrays using loops. Here’s an example using a for
loop:
for i := 0; i < len(numbers); i++ {
fmt.Println(numbers[i])
}
Key Takeaways
- Arrays in Go are fixed-size sequences of elements of the same type.
- You declare arrays using the
[size]dataType
syntax. - Arrays can be initialized during declaration or later using literals.
- Accessing and modifying array elements use zero-based indexing.
- Iterating through arrays is commonly done using loops.
Conclusion
Arrays are a fundamental building block in Go programming. Understanding how to declare, initialize, manipulate, and iterate through arrays is essential for any Go developer. With the knowledge gained from this tutorial and the provided examples, you should be well-equipped to work with arrays in your Go projects.