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 phython如何实现以下功能?查找同一用户名的消费金额合并—
- ¥15 孟德尔随机化怎样画共定位分析图
- ¥18 模拟电路问题解答有偿速度
- ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
- ¥15 误删注册表文件致win10无法开启
- ¥15 请问在阿里云服务器中怎么利用数据库制作网站
- ¥60 ESP32怎么烧录自启动程序
- ¥50 html2canvas超出滚动条不显示
- ¥15 java业务性能问题求解(sql,业务设计相关)
- ¥15 52810 尾椎c三个a 写蓝牙地址