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.9k Golang : Compress and decompress file with compress/flate example
+10.1k Golang : Print how to use flag for your application example
+27.5k PHP : Convert(cast) string to bigInt
+4.7k Facebook : How to place save to Facebook button on your website
+17k Golang : Get number of CPU cores
+10.2k Golang : cannot assign type int to value (type uint8) in range error
+9k Golang : How to use Gorilla webtoolkit context package properly
+7.9k Javascript : Put image into Chrome browser's console
+14.2k Golang : Get uploaded file name or access uploaded files
+20.7k Golang : Convert date string to variants of time.Time type examples
+9.9k Golang : Check if user agent is a robot or crawler example
+11.9k Golang : Convert decimal number(integer) to IPv4 address