Sorting 对具有公共字段的不同结构进行排序的最佳解决方案
我有像这样的结构类型Sorting 对具有公共字段的不同结构进行排序的最佳解决方案,sorting,go,Sorting,Go,我有像这样的结构类型 type A struct { Name string CreatedAt time.Time ... } type B struct { Title string CreatedAt time.Time ... } type C struct { Message string CreatedAt time.Time ... } 和普通切片 var result []interface{} 包
type A struct {
Name string
CreatedAt time.Time
...
}
type B struct {
Title string
CreatedAt time.Time
...
}
type C struct {
Message string
CreatedAt time.Time
...
}
和普通切片
var result []interface{}
包含A、B和C元素以及未来将出现的更多元素
我想按“CreatedAt”对切片进行排序
最好的解决方案是什么?我想避免检查类型或铸造 无论如何,让一个切片同时包含这两种类型的唯一方法是,该切片包含由这两种类型(包括接口{})实现的一些接口 您可能希望使用sort包并在切片上实现sort.Interface。解决方案有点冗长,但很有意义:
type Creation interface {
GetCreated() time.Time
}
type A struct {
Name string
CreatedAt time.Time
}
func (a *A) GetCreated() time.Time {
return a.CreatedAt
}
func (a *A) String() string {
return a.Name
}
type B struct {
Title string
CreatedAt time.Time
}
func (b *B) GetCreated() time.Time {
return b.CreatedAt
}
func (b *B) String() string {
return b.Title
}
type AorB []Creation
func (x AorB) Len() int {
return len(x)
}
func (x AorB) Less(i, j int) bool {
// to change the sort order, use After instead of Before
return x[i].GetCreated().Before(x[j].GetCreated())
}
func (x AorB) Swap(i, j int) {
x[i], x[j] = x[j], x[i]
}
func main() {
a := &A{"A", time.Now()}
time.Sleep(1 * time.Second)
b := &B{"B", time.Now()}
aOrB := AorB{b, a}
fmt.Println(aOrB)
// [B A]
sort.Stable(aOrB)
fmt.Println(aOrB)
// [A B]
}
A和B是否共享一个接口?这与一般意义上的排序值有何不同?@JimB可能是在问一些通用的问题,以对具有公共属性的不同结构进行排序field@guillaume06A和B如何存储在切片中?切片看起来像什么?最好的解决方案是有争议的。您尝试过什么?最平滑的方法可能是使用返回CreatedAt日期的方法定义一个接口,并使您的切片成为该接口的切片,以便您可以根据方法返回值进行排序。或者,您可以将CreatedAt字段放在另一个结构中,并将其嵌入到每个类型中。这将允许您定义GetCreated一次,并在您的结构中共享实现和字段定义,而不是在每个类型上重复它。