Published on

How to sort slice in Golang?

How to sort slice in Golang?

Sort a Slice in Golang

In Go (Golang), you can sort a slice using the built-in sort package. The sort package provides functions to sort slices of various types.

Here's a step-by-step explanation with an example of how to sort a slice in Go:

1. Import the sort package:

First, import the sort package at the beginning of your Go file:

    import "sort"

2. Create the Slice:

Define and populate the slice you want to sort. For this example, let's consider sorting a slice of integers:

    package main

    import (
        "fmt"
        "sort"
    )

    func main() {
        numbers := []int{9, 4, 7, 2, 1, 5, 8, 3, 6}
    }

3. Sorting the Slice:

To sort the slice, you can use the sort.Sort() function, passing a slice-compatible type that implements the sort.Interface interface. Alternatively, you can use the more convenient sort.Ints() function for slices of integers. Here, we'll use sort.Ints():

    package main

    import (
        "fmt"
        "sort"
    )

    func main() {
        numbers := []int{9, 4, 7, 2, 1, 5, 8, 3, 6}

        // Sorting the slice of integers
        sort.Ints(numbers)

        fmt.Println(numbers)
    }

4. Printing the Sorted Slice:

After sorting, you can print the sorted slice to see the result:

    package main

    import (
        "fmt"
        "sort"
    )

    func main() {
        numbers := []int{9, 4, 7, 2, 1, 5, 8, 3, 6}

        // Sorting the slice of integers
        sort.Ints(numbers)

        fmt.Println(numbers) // Output: [1 2 3 4 5 6 7 8 9]
    }

That's it! You've successfully sorted a slice of integers using the sort package in Go. The same approach can be used to sort slices of other types as well. Just make sure to use the appropriate sort function (e.g., sort.Strings() for strings) and ensure your slice type implements the sort.Interface methods if you choose to use sort.Sort() for custom sorting logic.