Let's say I have struct SortableStruct
with 3 fields A
B
C
I want to implement function that consumes sl []SortableStruct
and orderFied string
where orderField
is one of struct's field. This function should retrun slice sorted by orderField
. Is there a way of doing this without huge switch case. It's not ovious for me how to implement sort.Interface
when I want compare structs by different fields.
按指定字段对结构切片排序
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- douceng7070 2018-10-27 19:30关注
Well, easiest way is to switch
field
type and assign a SORT function. Here is your code:package main import ( "fmt" "sort" ) type SortableStruct struct { A int B int C int } func sortStruct(arr []SortableStruct, field string) { var less func(i, j int) bool switch field { case "B": less = func(i, j int) bool { return arr[i].B < arr[j].B } case "C": less = func(i, j int) bool { return arr[i].C < arr[j].C } default: less = func(i, j int) bool { return arr[i].A < arr[j].A } } sort.Slice(arr, less) } func main() { arr := []SortableStruct{ { A: 1, B: 5, C: 3, }, { A: 2, B: 3, C: 20, }, { A: -1, B: -1, C: 10, }, } sortStruct(arr, "C") fmt.Println(arr) }
Another idea would be to have 3 defined types, each of them implementing interface
sort.Interface
type SortableStructByA []SortableStruct type SortableStructByB []SortableStruct type SortableStructByC []SortableStruct
And then, you will have to cast your slice to the wanted type(depending on sort you want) and to do something like this:
sortableSlice := SortableStructByA(arr) sort.Sort(sortableSlice)
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 基于卷积神经网络的声纹识别
- ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
- ¥100 为什么这个恒流源电路不能恒流?
- ¥15 有偿求跨组件数据流路径图
- ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
- ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
- ¥15 CSAPPattacklab
- ¥15 一直显示正在等待HID—ISP
- ¥15 Python turtle 画图
- ¥15 stm32开发clion时遇到的编译问题