Arrays and Slices in Go
Introduction
Arrays and slices are fundamental data types in GoLang. They both allow you to store a collection of elements, but they have some key differences. In this guide, we will explore the differences between arrays and slices in GoLang and how to work with them effectively.
Arrays
An array is a fixed-size sequence of elements of the same type. The size of an array is determined at compile-time and cannot be changed during runtime. To define an array, you specify its type followed by the length within square brackets.
For example, let's declare an array called numbers
that can hold 5 integers:
var numbers [5]int
To access individual elements in an array, you use their zero-based indices. For instance, numbers[0]
refers to the first element in the array.
You can initialize an array with values using a literal syntax:
var numbers = [5]int{1, 2, 3}
Or you can let go assign default values for empty slots when declaring:
var numbers = [...]int{1, 2, 3}
Keep in mind that once the size of an array is defined during compilation time it cannot be changed later on.
Slices
Unlike arrays,
slices are dynamic collections that can grow or shrink during runtime.
A slice does not have a predefined size - it is essentially a pointer to an underlying array.
To declare a slice,
you use similar syntax used for arrays but without specifying its length unless necessary:
var numbers []int // Empty slice declaration
or
numbers := make([]int ,10)//Creating dynamic sized empty slice with len 10 using built-in make() function.
You can also create slices from existing arrays using the slicing operation:
SliceName:=ArrayName[ FirstElementIncluded:LastElementNotIncluded]
numbers := [5]int{1, 2, 3, 4, 5}
var sliceNumbers []int = numbers[1:4]
In the example above,
sliceNumbers
will reference numbers[1]
, numbers[2]
, and numbers[3]
.
To append new elements to a slice,
you can use the built-in append()
function:
var numbers []int
numbers = append(numbers, 1)
numbers = append(numbers, 2, 3)
Note that when appending multiple elements at once,
you need to separate them by commas.
Conclusion
Arrays and slices are powerful data structures in GoLang for storing collections of elements.
Arrays have a fixed size determined during compilation time,
while slices are dynamic and allow resizing during runtime. Understanding how they work and their differences is crucial to writing efficient GoLang programs.
Keep practicing with arrays and slices to become more comfortable working with them!
Top comments (0)