为了账号安全,请及时绑定邮箱和手机立即绑定

如何调用实现接口的结构的特定方法

如何调用实现接口的结构的特定方法

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 关注
  • 96 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号