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
+7.2k Swift : Convert (cast) Character to Integer?
+8.6k Golang : Sort and reverse sort a slice of integers
+6.5k Golang : Gorrila set route name and get the current route name
+2.6k Java : Get FX sentiment from website example
+5.7k CloudFlare : Another way to get visitor's real IP address
+6.8k Swift : Convert (cast) String to Double
+21.6k Golang : Gorilla mux routing example
+28.6k Golang : Remove characters from string example
+10.1k Golang : Post data with url.Values{}
+17.2k Golang : Example for RSA package functions
+9.7k Golang : Delay or limit HTTP requests example
+21.9k Golang : Fix type interface{} has no field or no methods and type assertions example