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条)

报告相同问题?

悬赏问题

  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多