Golang有一个问题困扰我.说我有两个结构:
type Dog struct {
Name string
Breed string
Age int
}
type Cat struct {
Name string
FavoriteFood string
Age int
}
Run Code Online (Sandbox Code Playgroud)
当我尝试进行排序[]*Dog和[]*Cat通过Age,我必须定义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 {//..}
Run Code Online (Sandbox Code Playgroud)
一个自然的想法是使用接口函数实现一些SortableByAge …