Go – Sort Slice of Strings

To sort a slice of strings in Go programming, use sort package. sort package offers sorting for builtin datatypes and user defined datatypes, through which we can sort a slice of strings.

The sorting or strings happen lexicographically. Meaning a is less than b, b is less than c, and so on.

The syntax to sort a slice of strings strSlice using sort package is

</>
Copy
sort.Strings(strSlice)

The sorting happens in-place. Therefore original slice of strings is modified.

By default, the sorting happens in ascending order. To sort in decreasing order, we may use sort.Reverse function.

Note that we have to import sort package prior to using sort.Strings() function.

Examples

In the following example, we will take a slice of strings, and sort them in ascending order using sort.Strings().

example.go

</>
Copy
package main

import (
	"fmt"
	"sort"
)

func main() {
	strSlice := []string{"e", "c", "d", "a", "b"}
	fmt.Println("Before sorting :", strSlice)
	sort.Strings(strSlice)
	fmt.Println("After  sorting :", strSlice)
}

Output

Before sorting : [e c d a b]
After  sorting : [a b c d e]

Now, we shall sort this slice of strings in decreasing order, using sort.Reverse function.

example.go

</>
Copy
package main

import (
	"fmt"
	"sort"
)

func main() {
	strSlice := []string{"e", "c", "d", "a", "b"}
	fmt.Println("Before sorting :", strSlice)
	sort.Sort(sort.Reverse(sort.StringSlice(strSlice)))
	fmt.Println("After  sorting :", strSlice)
}

Output

Before sorting : [e c d a b]
After  sorting : [e d c b a]

Conclusion

In this Golang Tutorial, we learned how to sort a Slice of Strings in Go programming language using sort package, with the help of example programs.