Arrays And Slices in Golang

Ömer Ceylan
4 min readOct 17, 2023

--

In Go (or Golang), arrays and slices are fundamental data structures for managing collections of data. While they share some similarities, they have important differences in terms of size and flexibility.

Arrays

  • An array in Go is a fixed-size data structure that stores elements of the same type.
  • You need to specify the size of the array when you declare it.
  • Once an array is defined, its size cannot be changed.
  • Arrays are often used when you know the exact number of elements you need in advance.

Here is an examples of declaring and initializing an array in Go:

var numbers [5]int // An integer array with a fixed size of 5
numbers = [5]int{1, 2, 3, 4, 5}
numbers := [...]int{1, 2, 3, 4, 5} // Size calculated automatically

Just like in other languages, you can perform various manipulations on arrays, although they might not be as extensive as slices.

Iteration

If the feature under development requires iteration over an array, it can be implemented as follows.

arr := [5]int{1, 2, 3, 4, 5}
for i := 0; i < len(arr); i++ {
fmt.Println(arr[i])
}

Adding Items

Arrays have a fixed size, so you cannot dynamically add or remove elements from them. If your feature development requires operations like adding or removing elements, using slices would be much more appropriate.

Updating Items

You can update items in an array by reassigning a new value to a specific index:

arr := [5]int{1, 2, 3, 4, 5}
arr[2] = 10

Deleting Items

Like adding items, you cannot directly delete items from an array. You may need to create a new array without the item you want to remove.

Searching

If you need to perform a search on arrays, you can use the standard library shown below.

target := 3
found := false
for _, value := range arr {
if value == target {
found = true
break
}
}

Sorting

You can sort an array using the sort package in the standard library:

import "sort"
arr := []int{5, 3, 1, 4, 2}
sort.Ints(arr)

Filtering

You can filter elements from an array based on a condition by creating a new slice and appending the elements that meet the condition:

original := []int{1, 2, 3, 4, 5}
filtered := []int{}
for _, value := range original {
if value > 2 {
filtered = append(filtered, value)
}
}

Reversing

You can reverse the order of elements in an array by swapping elements:

arr := []int{1, 2, 3, 4, 5}
for i, j := 0, len(arr)-1; i < j; i, j = i+1, j-1 {
arr[i], arr[j] = arr[j], arr[i]
}

Concatenating

You can concatenate two or more arrays or slices by creating a new slice and appending the elements from the original arrays/slices.

Remember that arrays in Go have a fixed size, and if you need dynamic resizing and more manipulation capabilities, consider using slices, which are more flexible for managing collections of data.

Slices

  • A slice, on the other hand, is a dynamically-sized, flexible view into the elements of an underlying array.
  • Slices are created using the make() function or by slicing an existing array, another slice, or a string.
  • Slices can grow or shrink as needed.
  • Slices are more commonly used in Go because they provide greater flexibility when working with collections of data.

Here is an example of declaring and initializing a slice in Go:

var numbers []int // A slice with no fixed size, initially nil
numbers = []int{1, 2, 3, 4, 5} // Initialize the slice

You can also create a slice by slicing an array:

arr := [5]int{1, 2, 3, 4, 5}
slice := arr[1:4] // This creates a slice containing elements at indices 1, 2, and 3 of the array

Appending Items

You can add items to a slice using the append function. It dynamically resizes the slice to accommodate the new items:

slice := []int{1, 2, 3}
slice = append(slice, 4, 5)

Updating Items

To update an item in a slice, simply assign a new value to the slice at the desired index:

slice := []int{1, 2, 3, 4, 5}
slice[2] = 10

Deleting Items

You can delete an item from a slice by creating a new slice without the item you want to remove:

slice := []int{1, 2, 3, 4, 5}
indexToDelete := 2
slice = append(slice[:indexToDelete], slice[indexToDelete+1:]...)

Slicing a Slice

You can create a new slice by slicing an existing slice, specifying the start and end indices. This operation extracts a subset of the original slice:

originalSlice := []int{1, 2, 3, 4, 5}
newSlice := originalSlice[1:4] // [2, 3, 4]

Copying Slices

You can create a copy of a slice using the copy function

sourceSlice := []int{1, 2, 3}
targetSlice := make([]int, len(sourceSlice))
copy(targetSlice, sourceSlice)

Sorting a Slice

You can sort a slice using the sort package in the standard library:

import "sort"
slice := []int{5, 3, 1, 4, 2}
sort.Ints(slice)

Filtering Items

You can create a new slice that contains only items meeting a specific condition:

originalSlice := []int{1, 2, 3, 4, 5}
filteredSlice := []int{}
for _, value := range originalSlice {
if value > 2 {
filteredSlice = append(filteredSlice, value)
}
}

Reversing a Slice

You can reverse the order of elements in a slice by swapping elements:

slice := []int{1, 2, 3, 4, 5}
for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {
slice[i], slice[j] = slice[j], slice[i]
}

If your project involves frequent use of operations like searching, filtering, sorting, and complex business logic development, the Linq package is a widely used package for such tasks. You can find detailed documentation in the repository.

In summary, arrays have a fixed size, while slices are dynamically-sized and provide more flexibility. Slices are used more frequently in Go for managing collections of data due to their versatility.

--

--

Ömer Ceylan
Ömer Ceylan

Written by Ömer Ceylan

Senior Software Developer at Trendyol

No responses yet