reverse an array in go

To reverse an array in Go, you can loop through the array from both ends and swap their elements until both the ends meet in the middle. Here's an implementation:

main.go
func reverseArray(arr []int) []int {
    for i := 0; i < len(arr)/2; i++ {
        j := len(arr) - i - 1
        arr[i], arr[j] = arr[j], arr[i]
    }
    return arr
}
168 chars
8 lines

This function takes an integer array as input and returns the reversed integer array. We loop through the array until the middle is reached (when i >= len(arr)/2). At each iteration, we swap the elements at indices i and j (which starts at len(arr) - i - 1). Once the loop finishes, we return the original array arr, which is now reversed.

related categories

gistlibby LogSnag