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
+14.6k Golang : Send email with attachment(RFC2822) using Gmail API example
+13.9k Golang : Get dimension(width and height) of image file
+15.2k Golang : Accurate and reliable decimal calculations
+11.6k Golang : Display a text file line by line with line number example
+8.7k Golang : How to join strings?
+4.8k Golang : A program that contain another program and executes it during run-time
+9.9k Golang : Ordinal and Ordinalize a given number to the English ordinal numeral
+10.2k Golang : Random Rune generator
+8.2k Golang : Emulate NumPy way of creating matrix example
+30k Golang : Get time.Duration in year, month, week or day
+4.7k Chrome : How to block socketloop.com links in Google SERP?
+11k Golang : Create S3 bucket with official aws-sdk-go package