[英]How to call specific method of struct that implements an interface
我有以下接口和一些實現它的結構:
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)
}
我的dealer{}
結構中的Sell
方法接收一個接口。 在這個方法中,我想調用一個只存在於實現接口的結構之一上而不存在於其他結構上的方法:
if automobile.EngineType() == "Electric" {
fmt.Printf("The battery capacity of the vehicle is %d KWh", automobile.Capacity())
}
請注意, Capacity()
僅存在於ev{}
中,但不存在於truck{}
中。 有沒有辦法做到這一點,而不必將此方法添加到強制所有實現使用它的接口?
您可以使用類型斷言檢查方法是否存在。 檢查該值(或更具體地說,它的類型)是否具有您要查找的方法,如果有,您可以調用它。
可以通過檢查值是否使用該單一方法實現接口來實現檢查方法:
if hc, ok := automobile.(interface {
Capacity() int
}); ok {
fmt.Printf("The battery capacity of the vehicle is %d KWh", hc.Capacity())
}
然后 output 將是(在Go Playground上嘗試):
Selling a vehicle with the following properties
Vehicle Type: Truck
Vehicle Number of wheels: 6
Vehicle Engine Type: Gasoline
---------------------------
Selling a vehicle with the following properties
Vehicle Type: Electric Vehicle
Vehicle Number of wheels: 4
Vehicle Engine Type: Electric
The battery capacity of the vehicle is 100 KWh
如果為它創建一個命名的接口類型會更好:
type HasCapacity interface {
Capacity() int
}
接着:
if hc, ok := automobile.(HasCapacity); ok {
fmt.Printf("The battery capacity of the vehicle is %d KWh", hc.Capacity())
}
Output 將是相同的,在Go Playground上試試這個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.