Welcome to the exciting world of Go programming! Today, we're going to dive deep into one of the fundamental data structures - Arrays. Specifically, we'll focus on array initialization in Go.
An array is a collection of elements of the same type, arranged in contiguous memory locations. In Go, arrays are statically-sized, meaning their size must be defined at compile time.
Initializing an array in Go can be done in two ways:
Explicit initialization is when we provide specific values to each element of the array during its declaration. Here's an example:
package main
import "fmt"
func main() {
// Defining an array with explicit initialization
var numbers = [5]int{1, 2, 3, 4, 5}
// Printing the array
fmt.Println(numbers)
}In this example, we created an array named numbers with a fixed size of 5 elements. Each element was initialized with a specific integer value.
š Note: The size of the array must be provided at the time of declaration.
Default initialization is when we don't provide any initial values, and the Go compiler initializes all the elements with their respective zero values. Here's an example:
package main
import "fmt"
func main() {
// Defining an array with default initialization
var numbers [5]int
// Printing the array
fmt.Println(numbers)
}In this example, we created an array named numbers with a fixed size of 5 elements. Since we didn't provide any initial values, the Go compiler initialized all elements to their respective zero values. For integers, the zero value is 0.
š Note: If we try to print a default-initialized array without assigning any values, it will print the array's memory address, not the values.
Go also supports multi-dimensional arrays, which can be thought of as arrays of arrays. Here's an example:
package main
import "fmt"
func main() {
// Defining a 2D array
var matrix [2][3]int
// Assigning values to the 2D array
matrix[0][0] = 1
matrix[0][1] = 2
matrix[0][2] = 3
matrix[1][0] = 4
matrix[1][1] = 5
matrix[1][2] = 6
// Printing the 2D array
fmt.Println(matrix)
}In this example, we created a 2D array named matrix with 2 rows and 3 columns. We then assigned values to each element and printed the array.
What happens when we don't provide any initial values while initializing a Go array?
And that's it for today! We hope you enjoyed learning about Go array initialization. In the next lesson, we'll delve deeper into arrays, discussing how to declare arrays with varying sizes, how to iterate through arrays, and more.
Stay tuned and keep coding! šÆš