按指定字段对结构切片进行排序

假设我有一个SortableStruct包含 3 个字段的结构A B C,我想实现使用的函数sl []SortableStructorderFied string其中orderField一个是结构的字段。此函数应重新运行按 排序的切片orderField。有没有办法在没有巨大开关盒的情况下做到这一点。sort.Interface当我想按不同字段比较结构时,如何实现对我来说并不难。



叮当猫咪
浏览 71回答 1
1回答

收到一只叮咚

嗯,最简单的方法是切换field类型并分配一个 SORT 函数。这是您的代码:package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "sort")type SortableStruct struct {&nbsp; &nbsp; A int&nbsp; &nbsp; B int&nbsp; &nbsp; C int}func sortStruct(arr []SortableStruct, field string) {&nbsp; &nbsp; var less func(i, j int) bool&nbsp; &nbsp; switch field {&nbsp; &nbsp; case "B":&nbsp; &nbsp; &nbsp; &nbsp; less = func(i, j int) bool {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return arr[i].B < arr[j].B&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; case "C":&nbsp; &nbsp; &nbsp; &nbsp; less = func(i, j int) bool {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return arr[i].C < arr[j].C&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; less = func(i, j int) bool {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return arr[i].A < arr[j].A&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; sort.Slice(arr, less)}func main() {&nbsp; &nbsp; arr := []SortableStruct{&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; A: 1,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; B: 5,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; C: 3,&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; A: 2,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; B: 3,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; C: 20,&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; A: -1,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; B: -1,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; C: 10,&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; }&nbsp; &nbsp; sortStruct(arr, "C")&nbsp; &nbsp; fmt.Println(arr)}另一个想法是定义 3 个类型,每个类型都实现接口sort.Interfacetype SortableStructByA []SortableStructtype SortableStructByB []SortableStructtype SortableStructByC []SortableStruct然后,您必须将切片转换为所需的类型(取决于您想要的类型)并执行如下操作:sortableSlice := SortableStructByA(arr)sort.Sort(sortableSlice)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go