golang的int64排序_Golang对结构体进行排序

1、方法一,通过实现sort.Interface接口来进行排序

这里直接上代码:

package main

import (

"fmt"

"sort"

)

type Student struct {

Name string //名称

IsOnline int64 //是否在线

Integral int64 //积分

Gold float64 //金币

}

type Students []*Student

// 实现sort.Interface接口取元素数量方法

func (c Students) Len() int {

return len(c)

}

// 实现sort.Interface接口比较元素方法

func (c Students) Less(i, j int) bool {

//先是否根据是否在线进行排序

if c[i].IsOnline != c[j].IsOnline {

return c[i].IsOnline > c[j].IsOnline

}

//在通过积分进行排序

if c[i].Integral != c[j].Integral {

return c[i].Integral > c[j].Integral

}

//最后通过金币排序

return c[i].Gold > c[j].Gold

}

// 实现sort.Interface接口交换元素方法

func (c Students) Swap(i, j int) {

c[i], c[j] = c[j], c[i]

}

func main() {

// 准备英雄列表

students := Students{

&Student{"吕布", 1, 12, 11.0},

&Student{"张飞", 0, 3, 12.1},

&Student{"关羽", 0, 6, 9.9},

&Student{"刘备", 1, 12, 0},

&Student{"诸葛亮", 1, 0, 1},

&Student{"曹操", 0, 1, 1000},

}

// 使用sort包进行排序

sort.Sort(students)

// 遍历英雄列表打印排序结果

for _, v := range students {

fmt.Printf("%+v\n", v)

}

}

结果:

>go run test.go

&{Name:吕布 IsOnline:1 Integral:12 Gold:11}

&{Name:刘备 IsOnline:1 Integral:12 Gold:0}

&{Name:诸葛亮 IsOnline:1 Integral:0 Gold:1}

&{Name:关羽 IsOnline:0 Integral:6 Gold:9.9}

&{Name:张飞 IsOnline:0 Integral:3 Gold:12.1}

&{Name:曹操 IsOnline:0 Integral:1 Gold:1000}

1、方法二,使用sort.Slice进行切片元素排序

package main

import (

"fmt"

"sort"

)

type Student struct {

Name string //名称

IsOnline int64 //是否在线

Integral int64 //积分

Gold float64 //金币

}

type Students []*Student

func main() {

// 准备英雄列表

students := Students{

&Student{"吕布", 1, 12, 11.0},

&Student{"张飞", 0, 3, 12.1},

&Student{"关羽", 0, 6, 9.9},

&Student{"刘备", 1, 12, 0},

&Student{"诸葛亮", 1, 0, 1},

&Student{"曹操", 0, 1, 1000},

}

// 使用sort包进行排序

sort.Slice(students, func(i, j int) bool {

//先是否根据是否在线进行排序

if students[i].IsOnline != students[j].IsOnline {

return students[i].IsOnline > students[j].IsOnline

}

//在通过积分进行排序

if students[i].Integral != students[j].Integral {

return students[i].Integral > students[j].Integral

}

//最后通过金币排序

return students[i].Gold > students[j].Gold

})

// 遍历英雄列表打印排序结果

for _, v := range students {

fmt.Printf("%+v\n", v)

}

}

结果:

>go run test.go

&{Name:吕布 IsOnline:1 Integral:12 Gold:11}

&{Name:刘备 IsOnline:1 Integral:12 Gold:0}

&{Name:诸葛亮 IsOnline:1 Integral:0 Gold:1}

&{Name:关羽 IsOnline:0 Integral:6 Gold:9.9}

&{Name:张飞 IsOnline:0 Integral:3 Gold:12.1}

&{Name:曹操 IsOnline:0 Integral:1 Gold:1000}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值