To reverse an array in Go, you can iterate through the array and swap elements from start to end until reaching the middle.
In this example,
intArray
containing integers.start
and end
to track the start and end indices of the array.start
to end
until start
is greater than or equal to end
(indicating we've reached the middle).package main
import "fmt"
func main() {
intArray := []int{1, 2, 3, 4, 5}
for start, end := 0, len(intArray)-1; start < end; start, end = start+1, end-1 {
intArray[start], intArray[end] = intArray[end], intArray[start]
}
fmt.Println("Reversed Array:", intArray)
}
Reversed Array: [5 4 3 2 1]
In this example,
strArray
containing strings.start
and end
to track the start and end indices of the array.start
to end
until start
is greater than or equal to end
(indicating we've reached the middle).package main
import "fmt"
func main() {
strArray := []string{"apple", "banana", "cherry"}
for start, end := 0, len(strArray)-1; start < end; start, end = start+1, end-1 {
strArray[start], strArray[end] = strArray[end], strArray[start]
}
fmt.Println("Reversed Array:", strArray)
}
Reversed Array: [cherry banana apple]
In this tutorial, we learned How to Reverse an Array in Go language with well detailed examples.