1 回答

TA貢獻1773條經(jīng)驗 獲得超3個贊
您可以使用類型斷言檢查方法是否存在。檢查該值(或更具體地說,它的類型)是否具有您要查找的方法,如果有,您可以調(diào)用它。
可以通過檢查值是否使用該單一方法實現(xiàn)接口來實現(xiàn)檢查方法:
if hc, ok := automobile.(interface {
Capacity() int
}); ok {
fmt.Printf("The battery capacity of the vehicle is %d KWh", hc.Capacity())
}
然后輸出將是(在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
如果為它創(chuàng)建一個命名的接口類型會更好:
type HasCapacity interface {
Capacity() int
}
接著:
if hc, ok := automobile.(HasCapacity); ok {
fmt.Printf("The battery capacity of the vehicle is %d KWh", hc.Capacity())
}
輸出將是相同的,在Go Playground上試試這個。
- 1 回答
- 0 關(guān)注
- 106 瀏覽
添加回答
舉報