GolangWebDev
GolangWebDev
342 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
0

See Also


Discussion

Login Topics