Welcome to our continuing adventure through Go's data structures! In this lesson, we'll shift our focus from slices to arrays. Let's dive in!
Arrays in Go are a fundamental way to store multiple items in a single variable, but unlike slices, their size is fixed upon creation. Arrays are explicitly defined with square brackets that specify the number of elements they hold. Let's track the cities you've planned to visit on your travels using an array:
Go1package main 2 3import "fmt" 4 5func main() { 6 // Create an array of cities 7 citiesPlanned := [5]string{"Paris", "Tokyo", "New York", "London", "Berlin"} 8 9 // Access and print an element from the array 10 fmt.Println("The second city planned to visit is:", citiesPlanned[1]) 11}
Now, we'll demonstrate how to access individual cities within your citiesPlanned
array. Each element is accessed using its index, similar to how you'd access elements in slices:
Go1// Access and print specific elements 2fmt.Println("First city:", citiesPlanned[0]) 3fmt.Println("Third city:", citiesPlanned[2]) 4fmt.Println("Fifth city:", citiesPlanned[4])
This approach allows you to directly access specific elements when you know their index positions.
It's crucial to understand that while the contents of an array can be altered, its size is immutable and cannot change after initialization. This means you need to know the number of items in advance:
Go1// Change an element in the array 2citiesPlanned[2] = "Sydney" 3fmt.Println("Updated city:", citiesPlanned[2])
Arrays offer a reliable way to store a predetermined number of items and provide benefits in terms of memory allocation efficiency for fixed-size collections.
This lesson delves into arrays in Go, highlighting their role as a fixed-size data structure for storing multiple items. Arrays are defined with a specific size using square brackets, and elements are accessed using indices. While the content of an array can be modified, its size is immutable after initialization, making arrays ideal for scenarios where the number of elements is predetermined.
Are you ready to expand your programming horizons with Go's arrays? Let's journey on and discover the power of Go's structured collections!