Welcome to this comprehensive guide on Go Array Declaration! In this lesson, we'll dive into the world of Go arrays, understanding why and how they work, and how to use them effectively in your projects.
An array in Go is a collection of elements, all of the same type, stored at contiguous memory locations. Arrays are a fundamental data structure in Go, providing a way to store and manipulate multiple values of the same type.
To declare a Go array, we use the arrayType arrayName [arrayLength] syntax. Let's create a simple array:
// Declare an integer array with 5 elements
var myArray [5]intIn the example above, myArray is our array name, and [5]int indicates that it's an array of 5 integers.
š Note: Go automatically initializes all array elements to their zero values (0 for numeric types, false for booleans, and nil for pointers and structs).
You can also initialize an array with specific values when you declare it:
// Initialize an integer array with specific values
var myColors = [3]string{"Red", "Green", "Blue"}In this example, myColors is an array of 3 strings, initialized with the specified values.
Go also supports multi-dimensional arrays, which are arrays of arrays:
// Declare a 3x3 matrix of integers
var myMatrix [3][3]int
// Initialize a 3x3 matrix
var my3x3 = [3][3]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}In the example above, myMatrix is a 3x3 matrix of integers, and my3x3 is a matrix initialized with specific values.
To access an array element, use the array name followed by the index in square brackets:
package main
import "fmt"
func main() {
// Declare an array of 5 integers
myArray := [5]int{1, 2, 3, 4, 5}
// Access the second element
fmt.Println(myArray[1]) // Output: 2
// Modify the third element
myArray[2] = 10
// Print the modified array
fmt.Println(myArray) // Output: [1 2 10 4 5]
}To find the length of a Go array, use the built-in len() function:
package main
import "fmt"
func main() {
// Declare an array of 5 integers
myArray := [5]int{1, 2, 3, 4, 5}
// Find the length of the array
fmt.Println(len(myArray)) // Output: 5
}fmt.Println() to print an array's elements.for loops to iterate over an array's elements.sort package's Sort() function to sort an array.[start:end]) to copy an array.Now that you've learned the basics of Go arrays, let's test your knowledge with a quiz:
What is the output of the following code?
That's it for this lesson! In the next lessons, we'll explore more advanced Go array topics like multi-dimensional arrays, slices, and array functions. Happy coding! šÆ