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
+5.2k Golang : Get missing location after unmarshal binary and gob decode time.
+19.1k Nginx + FastCGI + Go Setup.
+6.8k Javascript : Put image into Chrome browser's console
+8.7k Golang : Populate slice with sequential integers example
+11.9k Generate salted password with OpenSSL example
+15k Golang : convert string or integer to big.Int type
+27.9k Golang : How to create new XML file ?
+18.8k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+36.6k Golang : Comparing date or timestamp
+13.8k Golang : Basic authentication with .htpasswd file
+10.9k Golang : Simple client-server HMAC authentication without SSL example