相关疑难解决方法(0)

如何避免重新实现类似golang结构的sort.Interface

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 …

coding-style interface go slice

8
推荐指数
2
解决办法
4845
查看次数

标签 统计

coding-style ×1

go ×1

interface ×1

slice ×1