Introduction
Collections are fundamental in programming for storing and manipulating data. In this guide, we'll explore arrays and maps in Go, and provide sample code to demonstrate how to work with these collection types.
Arrays in Go
An array in Go is a fixed-size collection of elements of the same type. Here's an example of declaring and using an array:
package main
import "fmt"
func main() {
// Declare an array of integers with a fixed size of 3.
var numbers [3]int
// Assign values to the array elements.
numbers[0] = 1
numbers[1] = 2
numbers[2] = 3
// Access and print array elements.
fmt.Println("Array:", numbers)
fmt.Println("Element at index 1:", numbers[1])
}
In this code, we declare an array of integers and access its elements using indices.
Slices in Go
Slices are a more flexible alternative to arrays in Go. They are dynamically sized and reference underlying arrays. Here's an example:
package main
import "fmt"
func main() {
// Create a slice of integers.
numbers := []int{1, 2, 3}
// Append an element to the slice.
numbers = append(numbers, 4)
// Access and print slice elements.
fmt.Println("Slice:", numbers)
fmt.Println("Element at index 2:", numbers[2])
}
Slices provide flexibility in managing collections, and you can use the append
function to add elements to a slice.
Maps in Go
A map in Go is an unordered collection of key-value pairs. It's ideal for representing associations between values. Here's an example of creating and using a map:
package main
import "fmt"
func main() {
// Create a map of string keys to int values.
age := map[string]int{
"Alice": 25,
"Bob": 30,
"Charlie": 35,
}
// Access and print map values.
fmt.Println("Age map:", age)
fmt.Println("Bob's age:", age["Bob"])
}
In this code, we create a map with string keys and integer values to represent ages.
Further Resources
To continue learning about arrays and maps in Go, consider these resources:
- Go Tour - More Types: Arrays, Slices, and Maps - An interactive online tutorial for learning Go collections.
- Effective Go - Arrays - Official Go documentation on arrays.
- Effective Go - Maps - Official Go documentation on maps.