1 回答

TA貢獻1839條經(jīng)驗 獲得超15個贊
如果索引 i 處的值小于索引 i 處的值,您需要提供的func應(yīng)該返回 true。sort.Slice
因此,您應(yīng)該將==
and!=
替換為<
,或 with>=
進行反向排序。
Go 沒有隱式類型大小寫,因此在您的less
func 中,您必須使用類型開關(guān)之類的東西檢查每個字段的類型,并根據(jù)您找到的類型處理比較。
例如:
sort.Slice(hives, func(i, j int) bool {
aInt := hives[i][gpi.SortBy]
bInt := hives[j][gpi.SortBy]
switch a := aInt(type) {
case int:
if b, ok := bInt.(int); ok {
return a < b
}
panic("can't compare dissimilar types")
case string:
if b, ok := bInt.(string); ok {
return a < b
}
panic("can't compare dissimilar types")
default:
panic("unknown type")
}
})
- 1 回答
- 0 關(guān)注
- 111 瀏覽
添加回答
舉報