Skip to main content

Arrays, Slices and Maps in Go

In this tutorial, we will explore three important data structures in the Go programming language: Arrays, Slices, and Maps. These data structures are crucial for handling and organizing data in Go. Let's take a closer look at each.

Arrays in Go

An array in Go is a sequence of elements defined by a specific length. The syntax to declare an array is as follows:

var arrayName [length]type

For example, an array of 5 integers can be declared like this:

var myArray [5]int

You can also initialize an array at the time of declaration:

myArray := [5]int{10, 20, 30, 40, 50}

The elements of an array can be accessed using their index. Arrays in Go are zero-based, which means the first element is at index 0.

fmt.Println(myArray[0]) // prints 10

Slices in Go

A slice in Go is a more flexible, powerful, and convenient alternative to arrays. Unlike arrays, slices do not have a fixed size, which makes them more versatile.

You can create a slice using the built-in make function:

mySlice := make([]int, 5)

This creates a slice of integers with a length and capacity of 5. You can also create a slice from an array:

myArray := [5]int{10, 20, 30, 40, 50}
mySlice := myArray[1:4]

This slice includes elements from index 1 to 3 (end index is exclusive).

Adding elements to a slice is done using the append function:

mySlice = append(mySlice, 60)

Maps in Go

A map in Go is an unordered collection of key-value pairs. It's similar to dictionaries in Python or objects in JavaScript.

A map can be declared using the following syntax:

var mapName map[keyType]valueType

For example, a map with string keys and int values can be declared like this:

var myMap map[string]int

To initialize a map, use the make function:

myMap = make(map[string]int)

You can add elements to the map like this:

myMap["one"] = 1

And access them using the key:

fmt.Println(myMap["one"]) // prints 1

Conclusion

Arrays, Slices, and Maps are fundamental data structures in Go that you'll use frequently. While they each have their own use cases, they all help organize and store data in your programs. Understanding how to use them effectively is crucial to becoming proficient in Go.

In this tutorial, we've covered how to declare, initialize, and manipulate these data structures. With this knowledge, you should be able to handle data more efficiently in your Go programs.