头图

golang 多维度排序

func main() {
    type PersonAge struct {
        Name  string
        Age   int
        Hight int
    }
    ps := []PersonAge{
        {"bo", 31, 333},
        {"ao", 42, 34},
        {"ao", 41, 23423},
        {"ao", 40, 23423},
        {"ao", 45, 12},
        {"co", 17, 3434},
        {"do", 26, 2343},
    }
    sort.Slice(ps, func(i, j int) bool {
        //!=  有大小时排序,相等时,下一个选项的优先级
        if ps[i].Name != ps[j].Name {
            return ps[i].Name < ps[j].Name
        }
        if ps[i].Hight != ps[j].Hight {
            return ps[i].Hight < ps[j].Hight
        }
        return ps[i].Age < ps[j].Age
    })
    log.Println(ps)

    return
}

结果

 [{ao 45 12} {ao 42 34} {ao 40 23423} {ao 41 23423} {bo 31 333} {co 17 3434} {do 26 2343}]

三四一十二
1 声望0 粉丝