Golang : How to reverse slice or array elements order
In this short tutorial, we will learn how to reverse the elements order inside a slice or array. Taking the example from a previous tutorial on how to reverse elements order in a map, we will reverse the elements order by
1. calculating the total length of the slice.
2. deduct 1 position.
3. then deduct the current element position to get the last element.
4. finally, append the last element into a new slice with reversed order.
Here you go!
package main
import "fmt"
func main() {
cities := [...]string{"New York", "Beijing", "Bangkok", "Adelaide", "Tokyo", "Seoul", "Zurich", "Seattle"}
fmt.Println("Before : ", cities)
reversed := []string{}
// reverse order
// and append into new slice
for i := range cities {
n := cities[len(cities)-1-i]
//fmt.Println(n) -- sanity check
reversed = append(reversed, n)
}
fmt.Println("After : ", reversed)
}
Output :
Before : [New York Beijing Bangkok Adelaide Tokyo Seoul Zurich Seattle]
After : [Seattle Zurich Seoul Tokyo Adelaide Bangkok Beijing New York]
See also : Golang : How to reverse elements order in map ?
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.2k Golang : Calculate US Dollar Index (DXY)
+51.9k Golang : How to get time in milliseconds?
+19.2k Golang : Check if directory exist and create if does not exist
+11.2k Golang : Calculate Relative Strength Index(RSI) example
+6.4k Golang : Handling image beyond OpenCV video capture boundary
+4.6k Javascript : Access JSON data example
+16.9k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+7.4k Golang : Gorrila set route name and get the current route name
+10.1k Golang : Print how to use flag for your application example
+11.1k Golang : Read until certain character to break for loop
+26.6k Golang : Encrypt and decrypt data with AES crypto
+21.4k Golang : How to read float value from standard input ?