How to Sort a Slice of String in Reverse in Golang

You can sort a slice of strings in reverse order using the sort.Sort() along with the sort.Reverse() and sort.StringSlice() function.

How to sort a slice of string in reverse

Follow the below steps to sort strings reverse in Golang.

  1. Convert the []string to sort.StringSlice, which makes the slice an instance of the sort.Interface interface.
  2. Reverse the standard ascending order of the elements included in the sort.StringSlice by using the sort.Reverse() function.
  3. Sort the reversed slice using the general sort.Sort() function.

Example

package main

import (
  "fmt"
  "sort"
)

func main() {
  string_slice := []string{"Ellie", "Joel", "Tommy", "Marlene"}

  sort.Strings(string_slice)
  fmt.Println(string_slice)

  sort.Sort(sort.Reverse(sort.StringSlice(string_slice)))
  fmt.Println(string_slice)
}

Output

[Ellie Joel Marlene Tommy]

[Tommy Marlene Joel Ellie]

You can see from the output that we sort the strings in reverse order using the sort.Sort(), sort.Reverse(), and sort.StringSlice() methods.

In the above code, we sort the string_slice in reverse order using the sort.Sort() function and passing the result of the sort.Reverse(sort.StringSlice(string_slice)) as the argument.

The sort.Reverse() function returns a new sort.Interface that will sort the elements in reverse order, and sort.StringSlice(string_slice) is a wrapper around the string_slice of String that implements the sort.Interface.

Finally, it prints the sorted string slice in reverse order using the fmt.Println() function.

Conclusion

Use the combination of sort.Sort(), sort.Reverse(), and sort.StringSlice() functions to sort a slice of strings in reverse order in Golang.

Further reading

How to Sort Int Reverse in Golang

How to Sort Float Reverse in Golang

Leave a Comment