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
+13.8k Golang : Activate web camera and broadcast out base64 encoded images
+14k Golang : How to check if a file is hidden?
+30.2k Golang : How to declare kilobyte, megabyte, gigabyte, terabyte and so on?
+18.7k Golang : Find IP address from string
+5.7k Swift : Get substring with rangeOfString() function example
+29.6k Golang : How to create new XML file ?
+14.6k Golang : Missing Bazaar command
+16.4k Golang : Loop each day of the current month example
+27.7k Golang : dial tcp: too many colons in address
+11.8k Golang : Find age or leap age from date of birth example
+5.3k Python : Create Whois client or function example