golang

Golang Reverse Slice

Slices are very useful in Go. They allow you to create a dynamically-sized allow which can shrink and expand based on the elements stored. To learn more about Go slices, check our tutorial on the topic.

In this brief article, we will learn how to reverse a slice.

Unlike other programming languages such as Python, Go does not have a pre-built method you can call and reverse a slice.

Hence, we will need to do it manually. The following are the steps we will follow to reverse a slice.

  1. Determine the length of the slice.
  2. Remove 1 position from the slice.
  3. Fetch the last element.
  4. Append the last element in a new slice in reversed order.

An example code is as shown:

package main
import "fmt"
funcmain() {
    slc := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    rev_slc := []int{}
    fori := rangeslc {
        // reverse the order
        rev_slc = append(rev_slc, slc[len(slc)-1-i])
    }
    fmt.Println(rev_slc)
}

The example above uses a for loop and the range operator to iterate the array. However, we use the len of the array, minus 1, minus the current iteration.

We then use the append method to append the new value to the reversed slice. The resulting slice is as shown:

$ go run reverse_slice.go

[10 9 8 7 6 5 4 3 2 1]

You can also use the length of the slice in reverse. An example is as shown:

rev_slc := []int{}
fori := len(slc) - 1; i>= 0; i-- {
    rev_slc = append(rev_slc, slc[i])
}
fmt.Println(rev_slc)

The above method functions closely similar to the one above but makes use of the decrement operator.

Conclusion

This was a brief article on how to reverse a slice in the Go programming language.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list