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
+12.1k Golang : Read from buffered reader until specific number of bytes
+3.5k Java : Generate multiplication table example
+10.4k Golang : Surveillance with web camera and OpenCV
+7.2k Golang : Metaprogramming example of wrapping a function
+3.5k Golang : Valued expressions and functions example
+26.4k Golang : Move file to another directory
+20.9k Golang : Read directory content with filepath.Walk()
+7k Golang : Multiplexer with net/http and map
+9.9k Golang : Read until certain character to break for loop
+19.8k Golang : Get password from console input without echo or masked
+11.4k Golang : HTTP response JSON encoded data
+5.2k Golang : How to solve "too many .rsrc sections" error?