dpqy77560 2017-04-04 15:04
浏览 56
已采纳

Golang接口分片

I wrote a CLI tool in Golang to wrap an API and I love how simple it was to put together. Now I want to incorporate another API with a different JSON structure to get similar values. I created an interface for the structs to implement, but I don't quite understand how the type casting works in Golang.

Here is an example I put together:

I have a common interface Vehicle that exposes some methods

type Vehicle interface {
    Manufacturer() string
    Model() string
    Year() int
    Color() string
    String() string
}

I also want to sort all structs that implement this interface so I added a Vehicles type that implements the sort interface

type Vehicles []Vehicle

func (s Vehicles) Len() int {
    return len(s)
}

func (s Vehicles) Less(i, j int) bool {
    if s[i].Manufacturer() != s[j].Manufacturer() {
        return s[i].Manufacturer() < s[j].Manufacturer()
    } else {
        if s[i].Model() != s[j].Model() {
            return s[i].Model() < s[j].Model()
        } else {
            return s[i].Year() < s[j].Year()
        }
    }
}

func (s Vehicles) Swap(i, j int) {
    s[i], s[j] = s[j], s[i]
}

The issue is when I implement the Vehicle interface with a new struct Car and try to sort a slice of Cars I get this exception

tmp/sandbox022796256/main.go:107: cannot use vehicles (type []Car) as type sort.Interface in argument to sort.Sort:
    []Car does not implement sort.Interface (missing Len method)

Here is the full code: https://play.golang.org/p/KQb7mNXH01

Update:

@Andy Schweig provided a good answer to the problem I posed, but i should have been more explicit that I am unmarshalling JSON into a slice of Car structs so his solution doesn't work in this more explicit case ( Please see the updated link to my code )

  • 写回答

3条回答 默认 最新

  • dongqie4233 2017-04-05 08:02
    关注

    The problem is that Car implements Vehicle, but []Car is not []Vehicle. One is a slice of objects and the other is a slice of interfaces. What you need as Andy Scheweig said, you need GetVehicles to return Vehicles ([]Vehicle). You can do the conversion inside the GetVehicles and afterwards if you need the Cars you can do type assertion.

    Made some changes to your code, and works as you need it now.

    https://play.golang.org/p/fM8EhSfsCU

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?