Golang : Sort and reverse sort a slice of strings
Tags : golang sort reverse-sort slice 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
Tags : golang sort reverse-sort slice strings
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
+2.1k Golang : How to determine if request or crawl is from Google robots
+1.8k Javascript : How to refresh page with JQuery ?
+2.3k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared
+7k Golang : Test file read write permission example
+10.7k Golang : dial tcp: too many colons in address
+2.6k Golang : Get YouTube playlist
+4.4k Golang : Count JSON objects and convert to slice/array
+1.4k Golang : Humanize and Titleize functions
+1.7k Golang : Display advertisement images or strings on random order
+2.2k Golang : Individual and total number of words counter example
+38.7k Golang : Upload file from web browser to server
+7.2k Golang : convert string or integer to big.Int type