Home  >  Article  >  Backend Development  >  How to Reverse Sort a Slice of Integers in Go?

How to Reverse Sort a Slice of Integers in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-11-12 11:51:02803browse

How to Reverse Sort a Slice of Integers in Go?

Reverse Sorting a Slice of Integers in Go

You seek to reverse-sort a slice of integers in Go, similar to how the built-in sort.Ints function sorts them from lowest to highest.

Custom Implementation:

You attempted to utilize sort.Ints followed by sort.Reverse, but encountered an error. The issue is that sort.Ints returns a value that cannot be used as a sort.Interface.

IntSlice Type:

The sort package conveniently provides IntSlice, a predefined type that implements the sort.Interface. By using this type, you can achieve reverse sorting with ease. Here's how to accomplish it:

package main

import (
    "fmt"
    "sort"
)

func main() {
    keys := []int{3, 2, 8, 1}
    sort.Sort(sort.Reverse(sort.IntSlice(keys)))
    fmt.Println(keys)
}

This code sorts the slice keys in reverse order, effectively from highest to lowest. The output will be:

[8 3 2 1]

The above is the detailed content of How to Reverse Sort a Slice of Integers in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn