我正在嘗試在 Go 中對整數切片進行反向排序。 example := []int{1,25,3,5,4} sort.Ints(example) // this will give me a slice sorted from 1 to the highest number我如何對其進行排序,使其從最高到最低?所以 [25 5 4 3 1]我試過這個sort.Sort(sort.Reverse(sort.Ints(keys)))來源:http : //golang.org/pkg/sort/#Reverse但是,我收到以下錯誤# command-line-arguments./Roman_Numerals.go:31: sort.Ints(keys) used as value
2 回答

料青山看我應如是
TA貢獻1772條經驗 獲得超8個贊
sort.Ints是一個方便的函數來對幾個整數進行排序。通常,如果要對某些內容進行排序,則需要實現sort.Interface接口,而sort.Reverse僅返回重新定義該Less方法的該接口的不同實現。
幸運的是 sort 包包含一個名為IntSlice的預定義類型,它實現了 sort.Interface:
keys := []int{3, 2, 8, 1}
sort.Sort(sort.Reverse(sort.IntSlice(keys)))
fmt.Println(keys)

藍山帝景
TA貢獻1843條經驗 獲得超7個贊
package main
import (
"fmt"
"sort"
)
func main() {
example := []int{1, 25, 3, 5, 4}
sort.Sort(sort.Reverse(sort.IntSlice(example)))
fmt.Println(example)
}
輸出:
[25 5 4 3 1]
- 2 回答
- 0 關注
- 280 瀏覽
添加回答
舉報
0/150
提交
取消