How to Sort a Slice of Strings in Golang?


Sorting a slice of string values is a common task in many applications, and Go provides a built-in package sort that includes functions to sort slices of any type, including slices of string values. In this article, we will discuss how to sort a slice of string values in Golang.

Go provides two functions for sorting slices of string values: sort.Strings() and sort.Slice(). The sort.Strings() function sorts a slice of string values in ascending order, while the sort.Slice() function allows for more customization by allowing you to provide a custom less function to determine the sort order.

Example

Here's an example of how to sort a slice of string values using sort.Strings() −

package main

import (
   "fmt"
   "sort"
)

func main() {
   names := []string{"Alice", "Bob", "Charlie", "David"}
   fmt.Println("Original slice:", names)

   sort.Strings(names)

   fmt.Println("Sorted slice:", names)
}

Output

Original slice: [Alice Bob Charlie David]
Sorted slice: [Alice Bob Charlie David]

In the above example, we create a slice of string values and print out the original slice. We then sort the slice in ascending order using the sort.Strings() function and print out the sorted slice.

Conclusion

Go provides built-in functions for sorting slices of string values in ascending order and allows for customization of the sort order using the sort.Slice() function and a custom less function. Understanding how to sort slices of string values is essential for writing efficient and effective Go code.

Updated on: 26-Apr-2023

988 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements