亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何調用實現接口的結構的特定方法

如何調用實現接口的結構的特定方法

Go
慕的地6264312 2022-06-21 16:52:38
我有以下接口和一些實現它的結構:package mainimport "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{}。有沒有辦法做到這一點,而不必將此方法添加到強制所有實現使用它的接口?
查看完整描述

1 回答

?
慕容3067478

TA貢獻1773條經驗 獲得超3個贊

您可以使用類型斷言檢查方法是否存在。檢查該值(或更具體地說,它的類型)是否具有您要查找的方法,如果有,您可以調用它。


可以通過檢查值是否使用該單一方法實現接口來實現檢查方法:


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

如果為它創建一個命名的接口類型會更好:


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上試試這個。


查看完整回答
反對 回復 2022-06-21
  • 1 回答
  • 0 關注
  • 113 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號