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
+3.5k Javascript : How to replace HTML inside <div>?
+31.3k Golang : convert(cast) bytes to string
+6.2k Golang : Check a web page existence with HEAD request example
+5.2k Golang : Generate Datamatrix barcode
+5.3k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared
+7.8k Golang : Display list of countries and ISO codes
+3.7k Golang : Error handling methods
+7.7k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+2.9k Unix/Linux : How to pipe/save output of a command to file?
+5.9k Golang : HTTP Server Example
+10.9k Golang : Delete files by extension
+3.2k Python : Convert(cast) string to bytes example