Transform and choose data representations

Reverse a Go Slice in Place or Without Changing the Original

Reverse a Go slice with an in-place loop, a separate result, or a copied slice passed to slices.Reverse. Learn which operations share storage.

By Niko Minadze4 min read

Editorial illustration for Reverse a Go Slice in Place or Without Changing the Original

If the caller expects its slice to change, swap elements from the two ends toward the middle. If the caller still needs the original order, allocate a result and fill it from the input in reverse. The important choice is not how to count backward. It is whether the result may share the input's storage.

Reverse in place with two indices

Keep left at the start and right at the end. Swap their elements, move both indices inward, and stop when they meet or cross. This is the two-index reversal shown in the Go Slice Tricks wiki. It works for odd and even lengths: an odd-length slice leaves its middle element where it is.

The following program also shows a separate-result helper, so the difference between the two calls is visible:

package main

import "fmt"

func reverseInPlace(numbers []int) {
    for left, right := 0, len(numbers)-1; left < right; left, right = left+1, right-1 {
        numbers[left], numbers[right] = numbers[right], numbers[left]
    }
}

func reversedCopy(input []int) []int {
    result := make([]int, len(input))
    for i := range input {
        result[i] = input[len(input)-1-i]
    }
    return result
}

func main() {
    odd := []int{1, 2, 3, 4, 5}
    reverseInPlace(odd)
    fmt.Println("odd after in-place reversal:", odd)

    even := []int{10, 20, 30, 40}
    reversed := reversedCopy(even)
    fmt.Println("separate result:", reversed)
    fmt.Println("original even slice:", even)

    var nilSlice []int
    reverseInPlace(nilSlice)
    empty := []int{}
    reverseInPlace(empty)
    fmt.Println("nil remains nil:", nilSlice == nil)
    fmt.Println("empty length:", len(empty))
}

The expected output is:

odd after in-place reversal: [5 4 3 2 1]
separate result: [40 30 20 10]
original even slice: [10 20 30 40]
nil remains nil: true
empty length: 0

For a nil or empty slice, right starts at -1. Because left < right is false, the swap never indexes the slice. Neither input needs a special case. The in-place helper returns nothing to make its mutation explicit: after the call, odd itself has the reversed order.

Build a separate reversed slice

reversedCopy uses make to create a destination with the same length as input. Each destination position receives the element at the corresponding position counted from the other end of input. The loop reads the input but never assigns to it, so even retains its order while reversed has the opposite order. The Go slices introduction documents allocating a slice with make and filling it by assigning elements.

This helper copies elements, not everything an element might refer to. For example, if the elements are themselves slices, the outer result has separate storage, but its elements can still refer to the same inner arrays. Choose a deeper copy only when the data inside those elements must also be independent.

A new slice value is not necessarily a new copy

Assigning a slice to another variable does not copy its elements. Re-slicing does not either: the Go slices introduction explains that a re-slice points to the original array, and changing an element through that view changes the original slice's element. Reversing an assigned slice value or a re-sliced view can therefore reorder elements visible through the original.

A newly allocated destination solves that storage problem for the slice itself. It does not turn an element assignment into a deep copy. That distinction matters most when elements contain references to mutable data, rather than plain values such as the integers above.

Use slices when your toolchain provides it

If your target toolchain includes the standard-library slices package, slices.Reverse expresses the in-place operation directly. To retain the input's order, allocate a separate slice, copy the elements into it, and reverse that copy:

package main

import (
    "fmt"
    "slices"
)

func main() {
    original := []string{"alpha", "beta", "gamma", "delta"}
    reversed := make([]string, len(original))
    copy(reversed, original)
    slices.Reverse(reversed)

    fmt.Println(reversed)
    fmt.Println(original)
}

The expected output is:

[delta gamma beta alpha]
[alpha beta gamma delta]

Reverse changes the slice passed to it. Here, copy fills separately allocated storage with the original elements before Reverse runs. Those elements are still shallow copies: referenced data inside them is not independently copied. Check that the toolchain you are targeting provides slices before using this version; the manual loops do not require that package.

Use the in-place form when changing the caller-visible order is intended and you want to avoid allocating another slice. Use a separate result when both orders need to remain available. In either case, decide whether shared data inside the elements needs its own copying before treating the result as fully independent.

Comments

No comments yet.

Leave a comment

Your comment appears after approval. Plain text only; links stay as text. Line breaks and indentation are kept.

Up to 5,000 characters. No account or email needed.

All articles

Type at least two characters.

Press <kbd>Esc</kbd> to closeOpen the search page