I've got the following interface and a few structs which implement it:
package main
import "fmt"
type vehicle interface {
vehicleType() string
numberOfWheels() int
EngineType() string
}
// -------------------------------------------
type truck struct {
loadCapacity int
}
func (t truck) vehicleType() string {
return "Truck"
}
func (t truck) numberOfWheels() int {
return 6
}
func (t truck) EngineType() string {
return "Gasoline"
}
// -------------------------------------------
type ev struct {
capacityInKWh int
}
func (e ev) vehicleType() string {
return "Electric Vehicle"
}
func (e ev) numberOfWheels() int {
return 4
}
func (e ev) EngineType() string {
return "Electric"
}
func (e ev) Capacity() int {
return e.capacityInKWh
}
// -------------------------------------------
type dealer struct{}
func (d dealer) sell(automobile vehicle) {
fmt.Println("Selling a vehicle with the following properties")
fmt.Printf("Vehicle Type: %s \n", automobile.vehicleType())
fmt.Printf("Vehicle Number of wheels: %d \n", automobile.numberOfWheels())
fmt.Printf("Vehicle Engine Type: %s \n", automobile.EngineType())
if automobile.EngineType() == "Electric" {
fmt.Printf("The battery capacity of the vehicle is %d KWh", automobile.Capacity())
//fmt.Printf("Here")
}
}
func main() {
volvoTruck := truck{
loadCapacity: 10,
}
tesla := ev{
capacityInKWh: 100,
}
myDealer := dealer{}
myDealer.sell(volvoTruck)
fmt.Println("---------------------------")
myDealer.sell(tesla)
}
Sell method in my dealer{} struct receives an interface. In this method I want to call a method that exists only on one of the structs that implement the interface but not in the others:
if automobile.EngineType() == "Electric" {
fmt.Printf("The battery capacity of the vehicle is %d KWh", automobile.Capacity())
}
Notice that Capacity() exists only in ev{} but not in truck{}. Is there a way to do this without having to add this method to the interface forcing all implementations to use it?