【发布时间】:2017-08-29 20:58:29
【问题描述】:
我用 Golang 编写了一个 CLI 工具来包装 API,我喜欢它的简单组合。现在我想合并另一个具有不同 JSON 结构的 API 以获得相似的值。我为要实现的结构创建了一个接口,但我不太了解 Golang 中的类型转换是如何工作的。
这是我整理的一个例子:
我有一个公开一些方法的通用接口 Vehicle
type Vehicle interface {
Manufacturer() string
Model() string
Year() int
Color() string
String() string
}
我还想对实现这个接口的所有结构进行排序,所以我添加了一个实现排序接口的 Vehicles 类型
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]
}
问题是当我使用新结构 Car 实现 Vehicle 接口并尝试对 Cars 的一部分进行排序时,我得到了这个异常
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)
这里是完整代码:https://play.golang.org/p/KQb7mNXH01
更新:
@Andy Schweig 为我提出的问题提供了一个很好的答案,但我应该更明确一点,我正在将 JSON 解组为 Car 结构的一部分,因此他的解决方案在这种更明确的情况下不起作用 (请参阅我的代码的更新链接)
【问题讨论】:
标签: go interface casting type-conversion