Dong.Ge

左手代码 右手江湖

golang 排序终极版

东哥's Avatar 2019-06-24

至此算是初窥门径,about golang sort.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package main

import (
"encoding/json"
"fmt"
"sort"
)

type ApiCouponInfo struct {
Id int64
CouponType int64 `json:"coupon_type"`
DiscountAmount int64 `json:"discount_amount"`
IncreaseLimit int64 `json:"increase_limit"`
UsedTime int64
ValidStart int64 `json:"valid_start"`
ValidEnd int64 `json:"valid_end"`
Amount int64
Loan int64
IsAvaliable int64 `json:"is_avaliable"`
CouponTag int64 `json:"coupon_tag"`
}

type CouponInfoList []ApiCouponInfo

func (s CouponInfoList) Len() int {
return len(s)
}

func (s CouponInfoList) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}

func (s CouponInfoList) Less(i, j int) bool {
if s[i].CouponType > s[j].CouponType {
return true
} else if s[i].CouponType < s[j].CouponType {
return false
}

if s[i].DiscountAmount > s[j].DiscountAmount {
return true
} else if s[i].DiscountAmount < s[j].DiscountAmount {
return false
}

if s[i].ValidEnd < s[j].ValidEnd {
return true
} else if s[i].ValidEnd > s[j].ValidEnd {
return false
}

if s[i].IsAvaliable != s[j].IsAvaliable {
return s[i].IsAvaliable < s[j].IsAvaliable
}
return false
}

func main() {
list := `{"list": [ { "amount": 1984, "coupon_type": 4, "discount_amount": 150, "fee": 265, "gst": 47, "id": 494, "increase_limit": 150, "interest_amount": 22, "loan": 1650 }, { "amount": 1924, "coupon_type": 4, "discount_amount": 100, "fee": 257, "gst": 46, "id": 487, "increase_limit": 100, "interest_amount": 21, "loan": 1600 }, { "amount": 1924, "coupon_type": 4, "discount_amount": 100, "fee": 257, "gst": 46, "id": 492, "increase_limit": 100, "interest_amount": 21, "loan": 1600 }, { "amount": 1704, "coupon_type": 1, "discount_amount": 100, "fee": 0, "gst": 0, "id": 493, "increase_limit": 100, "interest_amount": 0, "loan": 1500 }, { "amount": 1724, "coupon_type": 1, "discount_amount": 80, "fee": 0, "gst": 0, "id": 491, "increase_limit": 80, "interest_amount": 0, "loan": 1500 }, { "amount": 1779, "coupon_type": 1, "discount_amount": 25, "fee": 0, "gst": 0, "id": 490, "increase_limit": 25, "interest_amount": 0, "loan": 1500 } ]}`
var oklist map[string]CouponInfoList
err := json.Unmarshal([]byte(list), &oklist)
if err != nil {
fmt.Println(err)
return
}
okInfo := oklist["list"]
for _, one := range okInfo {
fmt.Println(one, "\n")
}
fmt.Println("=====================\n")
sort.Sort(okInfo)
for _, one := range okInfo {
fmt.Println(one, "\n")
}
}

本文最后更新于 天前,文中所描述的信息可能已发生改变