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
+10.8k Golang : How to determine a prime number?
+8.6k Golang : Find network service name from given port and protocol
+33.6k Golang : Proper way to set function argument default value
+15.9k Golang : Loop each day of the current month example
+17.3k Golang : [json: cannot unmarshal object into Go value of type]
+7.4k Golang : Mapping Iban to Dunging alphabets
+22.7k Golang : Read a file into an array or slice example
+15.1k Golang : ROT47 (Caesar cipher by 47 characters) example
+19.5k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+21.2k Golang : Encrypt and decrypt data with TripleDES
+12.3k Golang : Remove or trim extra comma from CSV
+4.5k PHP : Extract part of a string starting from the middle