Go – Rotate an array in Golang

Hello everyone, in this tutorial, we will show you how to rotate an array in golang programming language. The example program has been tested and shared in the post.

Function – Rotate an array in Golang

The below two functions are responsible to rotate a given integer array. The leftRotate() function will perform array rotation based on the count and leftRotatebyOne() will do the rotate only one time.

// function rotate based on the count
func leftRotate(arr []int, count int) {
for i := 0; i < count; i++ {
leftRotatebyOne(arr); // calling function to perform rotation ont time
}
}

// function perform left rotate only one time
func leftRotatebyOne(arr []int) {

var i int = 0

var temp int = arr;

for ; i < len(arr) - 1; i++ {
arr[i] = arr[i+1];
}

arr[i] = temp;
}

Full Example

package main

import "fmt"

func main() {

// defining integer array
var numbers []int = []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

fmt.Println("Before Rotate:", numbers)

// calling a function to rotate an array
leftRotate(numbers, 3)

fmt.Println("After Rotate:", numbers)
}

// function rotate based on the count
func leftRotate(arr []int, count int) {
for i := 0; i < count; i++ {
leftRotatebyOne(arr); // calling function to perform rotation ont time
}
}

// function perform left rotate only one time
func leftRotatebyOne(arr []int) {

var i int = 0

var temp int = arr;

for ; i < len(arr) - 1; i++ {
arr[i] = arr[i+1];
}

arr[i] = temp;
}

Output

Before Rotate: [1 2 3 4 5 6 7 8 9 10]

After Rotate: [4 5 6 7 8 9 10 1 2 3]