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[0]; 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[0]; 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]
References
- https://www.geeksforgeeks.org/array-data-structure/#rotation
- https://en.wikipedia.org/wiki/Array_data_structure
More from my site

Hello, folks, I am a founder of idineshkrishnan.com. I love open source technologies, If you find my tutorials are useful, please consider making donations to these charities.
No responses yet