OneBite.Dev - Coding blog in a bite size

reverse arrays items in Go

Code snippet on how to reverse arrays items in Go

  package main

import "fmt"

func main() {
  //Declare an array of ints
  array := []int{1, 2, 3, 4, 5}

  //Iterate through the array from the end to the beginning
  for left, right := 0, len(array)-1; left < right; left, right = left+1, right-1 {
    //Swap the elements
    array[left], array[right] = array[right], array[left]
  }

  fmt.Println(array)
}

This code starts by declaring an array of integers and then a for loop is used to iterate through the array starting at the end and going to the beginning. During each iteration of the loop the current element and the element preceding it are swapped. At the end the modified array is printed out. This method of reversing an array takes an array of size n and takes O(n) time to complete.

go