在golang中比较一个数据中结构体的大小,可以使用如下的方式:
实现Swap Len Less三个方法即可。
下面直接上货:
type T []tt
type tt struct {
roomId int64
score float64
gameMin float64
}
func (t T) Swap(i, j int) {
t[i], t[j] = t[j], t[i]
}
func (t T) Len() int {
return len(t)
}
//排序规则
func (t T) Less(i, j int) bool {
if t[i].score < t[i].gameMin && t[j].score < t[j].gameMin {
return t[i].score <= t[j].score
} else if t[i].score < t[i].gameMin && t[j].score > t[j].gameMin {
return true
} else if t[i].score > t[i].gameMin && t[j].score < t[j].gameMin {
return false
} else {
return t[i].score >= t[j].score
}
}
func TestBB(t *testing.T) {
a := []int{3, 4, 1, 6, 7, 3, 2, 4, 7, 8, 3, 2}
sort.Ints(a)
fmt.Println(a)
var z = T{
{
roomId: 1,
score: 1.9,
gameMin: 2,
},
{
roomId: 2,
score: 1.6,
gameMin: 2,
},
{
roomId: 3,
score: 2.3,
gameMin: 2,
}, {
roomId: 9,
score: 0.6,
gameMin: 2,
}, {
roomId: 4,
score: 0.1,
gameMin: 2,
}, {
roomId: 8,
score: 2.1,
gameMin: 2,
},
}
fmt.Println(z)
sort.Sort(z)
fmt.Println(z)
var z2 []tt
var z3 []tt
for _, k := range z {
if k.score < 1 {
z2 = append(z2, k)
} else {
z3 = append(z3, k)
}
}
fmt.Println(z2)
fmt.Println(z3)
var realZ []tt
realZ = append(z3, z2...)
fmt.Println(realZ)
}
简单总结就是实现Swap Less Len从而实现 比较。
本文来源0day__,由javajgs_com转载发布,观点不代表Java架构师必看的立场,转载请标明来源出处
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有