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

后端 未结 3 1251
执念已碎
执念已碎 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:50

    Note: as illustrated in commit ad26bb5, in Go 1.8 (Q1 2017), you won't have to implement Len() and Swap() and Less() since issue 16721 was resolved. Only Less() is needed, the rest is done by reflection.

    The problem was:

    1. Vast majority of sort.Interface uses a slice
    2. Have to define a new top level type
    3. Len and Swap methods are always the same
    4. Want to make common case simpler with least hit to performance

    See the new sort.go:

    // Slice sorts the provided slice given the provided less function.
    //
    // The sort is not guaranteed to be stable. For a stable sort, use
    // SliceStable.
    //
    // The function panics if the provided interface is not a slice.
    func Slice(slice interface{}, less func(i, j int) bool) {
        rv := reflect.ValueOf(slice)
        swap := reflect.Swapper(slice)
        length := rv.Len()
        quickSort_func(lessSwap{less, swap}, 0, length, maxDepth(length))
    }
    

    So as long as you have a Less() function comparing two instances respecting an interface, you can sort any number of struct respecting said common interface.

提交回复
热议问题