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.
- Determine the length of the slice.
- Remove 1 position from the slice.
- Fetch the last element.
- Append the last element in a new slice in reversed order.
An example code is as shown:
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:
[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:
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.