我有以下接口和一些实现它的结构:
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我的dealer{}结构中的方法接收一个接口。在这个方法中,我想调用一个只存在于实现接口的结构之一上而不存在于其他结构上的方法:
if automobile.EngineType() == "Electric" {
fmt.Printf("The battery capacity of the vehicle is %d KWh", automobile.Capacity())
}
请注意,Capacity()它只存在于ev{}而不存在于 中truck{}。有没有办法做到这一点,而不必将此方法添加到强制所有实现使用它的接口?
慕容3067478
相关分类