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
+9.2k Golang : Convert(cast) uintptr to string example
+9.9k Golang : reCAPTCHA example
+8.9k Golang : md5 hash of a string
+19.7k Golang : Print out struct values in string format
+10.1k Golang : Gin framework accept query string by post request example
+14.3k Golang : Simple client server example
+14.4k Golang : Generate MD5 checksum of a file
+2.8k Nginx and PageSpeed build from source CentOS example
+6.8k Golang : Turn string or text file into slice example
+7.2k Golang : Copy map(hash table) example
+7.6k Golang : Meaning of omitempty in struct's field tag