Golang : Sort and reverse sort a slice of strings
Sometimes we will want to sort or reverse sort a collection of strings alphabetically. It is pretty easy to sort a slice of strings in Go. Just declare the slice as type sort.StringSlice
and use the Sort
method.
Here’s an example of sorting slice of Strings in Go.
package main
import (
"fmt"
"sort"
)
var strSlice sort.StringSlice = []string{"apple", "durian", "kiwi", "banana"}
func main() {
fmt.Println("Original : ", strSlice[:])
strSlice.Sort()
fmt.Println("Sort : ", strSlice[:])
sort.Sort(sort.Reverse(strSlice[:]))
fmt.Println("Reverse : ", strSlice[:])
}
Output :
Original : [apple durian kiwi banana]
Sort : [apple banana durian kiwi]
Reverse : [kiwi durian banana apple]
See also : Golang : Sort and reverse sort a slice of integers
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
+8.8k Golang : Capture text return from exec function example
+12.8k Golang : List objects in AWS S3 bucket
+8.9k Golang : does not implement flag.Value (missing Set method)
+29k Golang : Save map/struct to JSON or XML file
+7.3k SSL : How to check if current certificate is sha1 or sha2 from command line
+14.2k Golang : Overwrite previous output with count down timer
+11.7k Golang : Convert a rune to unicode style string \u
+6.9k CloudFlare : Another way to get visitor's real IP address
+7.9k Golang : Routes multiplexer routing example with regular expression control
+10.9k Golang : How to pipe input data to executing child process?
+6.4k Golang : How to validate ISBN?
+7.6k Setting $GOPATH environment variable for Unix/Linux and Windows