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.7k Golang : Random integer with rand.Seed() within a given range
+5.8k How to let Facebook Login button redirect to a particular URL ?
+5.1k Golang : Experimenting with the Rejang script
+14.5k Golang : Read large file with bufio.Scanner cause token too long error
+4.9k Golang : List all packages and search for certain package
+40.2k Golang : Convert string to array/slice
+27.9k Golang : JQuery AJAX post data to server and send data back to client example
+4.5k Clean up Visual Studio For Mac installation failed disk full problem
+11.2k Golang : How to check if a string starts or ends with certain characters or words?
+13.1k Golang : Recombine chunked files example
+16.4k Golang : Upload/Receive file progress indicator
+11.2k Golang : Validate email address