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 )