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 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址