Go – Reverse an Array in Golang

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

Reverse an array in golang
Go – Reverse an Array in Golang

Function – Reverse an array in Golang

The bellow function reverse() is responsible to reverse a given integer array.

func reverse(numbers []int) []int {
var length int = len(numbers) // getting length of an array
for i := 0; i < length/2; i++ {
temp := numbers[i]
numbers[i] = numbers[length - i - 1]
numbers[length - i - 1] = temp
}
return numbers
}

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}
// calling reverse function
numbers = reverse(numbers)
// printing the result
fmt.Println(numbers)
}
// function to reverse the given integer array
func reverse(numbers []int) []int {
var length int = len(numbers) // getting length of an array
for i := 0; i < length/2; i++ {
temp := numbers[i]
numbers[i] = numbers[length - i - 1]
numbers[length - i - 1] = temp
}
return numbers
}

Output

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

References

  1. https://idineshkrishnan.com/tag/golang/

Tags:

No Responses

Leave a Reply

Your email address will not be published.