type Dog struct {
Name string
Breed string
Age int
}
type Cat struct {
Name string
FavoriteFood string
Age int
}
当我尝试按年龄
对[]*Dog
和[]*Cat
进行排序时,我需要定义2个不同的排序结构,如下:
type SortCat []*Cat
func (c SortCat) Len() int {//..}
func (c SortCat) Swap(i, j int) {//..}
func (c SortCat) Less(i, j int) bool {//..}
type SortDog []*Dog
func (c SortDog) Len() int {//..}
func (c SortDog) Swap(i, j int) {//..}
func (c SortDog) Less(i, j int) bool {//..}
一个自然的想法是实现一些 SortableByAge
接口,然后使用接口函数创建一个 Less
函数。例如:
type SortableByAge interface {
AgeValue() int
}
然后:
type SortAnimal []SortableByAge
func (c SortDog) Less(i, j int) bool {
return c[i].AgeValue() < c[j].AgeValue()
}
然而,根据: http://golang.org/doc/faq#convert_slice_of_interface
dogs := make([]*Dogs, 0 , 1)
//add dogs here
sort.Sort(SortAnimal(dogs))
以上是不可能的。
因此,我想知道这种情况下最佳实践是什么,
是否有其他技术可以减少需要再次为类似结构实现sort.Interface
的需求,我错过了什么?
编辑: 我意识到我的示例很糟糕:(
在实际情况中,这两个结构非常不同,它们之间唯一的共同点是我希望按一个共同的数值对它们进行排序。
一个更好的例子是:
type Laptop {//...}
type Pizza {//...}
这两个结构体唯一共同之处是我想通过价格对它们的切片进行排序(啊...在示例中不应该使用Pizza
)。
因此,将它们合并为一个通用结构体对许多情况并不起作用。 但会研究go generate。
type Animal { Species, Name string; Age int }
。并不是所有不同的现实类别都必须映射到程序中的不同类型。 - twotwotwo