GolangWebDev
GolangWebDev
481 0 0

Only reverse a Slice in go

The standard library does not have a built-in function for reversing a slice. Use a for loop to reverse a slice:

for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
    s[i], s[j] = s[j], s[i]
}

Use type parameters to write a generic reverse function in Go 1.18 or later:

func ReverseSlice[S ~[]E, E any](s S)  {
    for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
        s[i], s[j] = s[j], s[i]
    }
}

func ReverseSlice2[T comparable](s []T) {
    sort.SliceStable(s, func(i, j int) bool {
        return i > j
    })
}

Benchmark:

goos: darwin
goarch: amd64
cpu: Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz
BenchmarkReverseSlice-8    	53480158	        19.01 ns/op	       0 B/op	       0 allocs/op
BenchmarkReverseSlice2-8   	  526812	      2227 ns/op	      56 B/op	       2 allocs/op

Key Points:

  • In-place reversal: Modifies the original slice directly.
  • Generic function: Works with any slice type ([]int, []string, etc.).
  • Efficiency: Runs in O(n) time with O(1) space complexity.
import "fmt"

func reverseSlice[T any](s []T) {
    for i := 0; i < len(s)/2; i++ {
        j := len(s) - 1 - i
        s[i], s[j] = s[j], s[i]
    }
}

func main() {
    // Example with integers
    nums := []int{1, 2, 3, 4, 5}
    reverseSlice(nums)
    fmt.Println(nums) // [5 4 3 2 1]

    // Example with strings
    words := []string{"hello", "world", "!"}
    reverseSlice(words)
    fmt.Println(words) // [! world hello]
}
0

See Also


Discussion

Login Topics