How to avoid re-implementing sort.Interface for similar golang structs

后端 未结 3 1253
执念已碎
执念已碎 2021-02-06 03:30

There is one problem bothering me in Golang. Say I have 2 structs:

type Dog struct {
   Name string
   Breed string
   Age int
}

type Cat struct {
    Name stri         


        
3条回答
  •  孤城傲影
    2021-02-06 03:48

    The best practice for this case would be to define

    type Animal struct{
        Species,Name string
        Age int
    }
    

    as suggested by twotwotwo. If cat and dog are similar enough to be sorted in the same way, they are also similar enough to be the same struct. If they are different in some way, then you should reimplement the interface for each type.

    An alternative could be to copy all pointers from your []*Cat slice into a []SortableByAge slice of the same size. If you are going to sort the slice, that will take O(n*log(n)) so an extra O(n) shouldn't be a performance issue.

    A third alternative, in the rare event that you have many types that for some reason have to be distinct but still have very simple sorting functions, you can look at autogenerating them with go generate.

提交回复
热议问题