Welcome to our tutorial on Go Array Access! In this lesson, we'll dive into the world of arrays in Go, a powerful programming language known for its simplicity and efficiency. By the end of this tutorial, you'll be comfortable working with arrays and understanding how they can be used in real-world projects. Let's get started!
Arrays are a collection of elements of the same data type, stored in contiguous memory locations. In Go, arrays are fixed in size, meaning you need to specify the number of elements when you create an array.
To create an array in Go, we use the arrayType[arraySize] syntax. Here's an example of creating an array of 5 integers:
numbers := [5]int{1, 2, 3, 4, 5}š” Pro Tip: You can also initialize an array without specifying the size, Go will automatically set the size based on the number of elements you provide.
To access an array element, you use the index number. Remember, indexing starts at 0, so the first element of an array is accessed with index 0. Here's how you can access elements from the numbers array we created earlier:
fmt.Println(numbers[0]) // Output: 1
fmt.Println(numbers[1]) // Output: 2You can modify an array element by reassigning a new value to the element's index:
numbers[0] = 10
fmt.Println(numbers) // Output: [10 2 3 4 5]In Go, there are two types of arrays:
To create a multidimensional array, you separate dimensions with commas:
matrix := [2][3]int{{1, 2, 3}, {4, 5, 6}}In this example, matrix is a 2x3 matrix (2 rows, 3 columns). You can access elements using two indexes: the first index represents the row, and the second index represents the column.
fmt.Println(matrix[0][0]) // Output: 1
fmt.Println(matrix[1][2]) // Output: 6To find the length of an array, you can use the built-in len function:
numLength := len(numbers)
fmt.Println(numLength) // Output: 5Let's create a simple program that calculates the average of a list of numbers:
package main
import "fmt"
func main() {
numbers := [5]int{1, 2, 3, 4, 5}
sum := 0
for i := 0; i < len(numbers); i++ {
sum += numbers[i]
}
average := float64(sum) / float64(len(numbers))
fmt.Printf("The average of the numbers is: %.2f\n", average)
}What is an array in Go?
We hope this tutorial has helped you understand arrays in Go! In the next lesson, we'll explore slices ā a more flexible data structure in Go. Happy coding! š” šÆ