简体   繁体   English

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

[英]How to call specific method of struct that implements an interface

I've got the following interface and a few structs which implement it:我有以下接口和一些实现它的结构:

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 method in my dealer{} struct receives an interface.我的dealer{}结构中的Sell方法接收一个接口。 In this method I want to call a method that exists only on one of the structs that implement the interface but not in the others:在这个方法中,我想调用一个只存在于实现接口的结构之一上而不存在于其他结构上的方法:

if automobile.EngineType() == "Electric" {
            fmt.Printf("The battery capacity of the vehicle is %d KWh", automobile.Capacity())
        }

Notice that Capacity() exists only in ev{} but not in truck{} .请注意, Capacity()仅存在于ev{}中,但不存在于truck{}中。 Is there a way to do this without having to add this method to the interface forcing all implementations to use it?有没有办法做到这一点,而不必将此方法添加到强制所有实现使用它的接口?

You may check for the existence of a method using a type assertion .您可以使用类型断言检查方法是否存在。 Check if the value (or more specifically its type) has the method you're looking for, and if it does, you may call it.检查该值(或更具体地说,它的类型)是否具有您要查找的方法,如果有,您可以调用它。

Checking for a method can be realized by checking if the value implements an interface with that single method:可以通过检查值是否使用该单一方法实现接口来实现检查方法:

if hc, ok := automobile.(interface {
    Capacity() int
}); ok {
    fmt.Printf("The battery capacity of the vehicle is %d KWh", hc.Capacity())
}

Then output will be (try it on the Go Playground ):然后 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

It's nicer if you create a named interface type for it:如果为它创建一个命名的接口类型会更好:

type HasCapacity interface {
    Capacity() int
}

And then:接着:

if hc, ok := automobile.(HasCapacity); ok {
    fmt.Printf("The battery capacity of the vehicle is %d KWh", hc.Capacity())
}

Output will be the same, try this one on the Go Playground . Output 将是相同的,在Go Playground上试试这个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何知道结构体或结构体指针是否实现了接口 - How to know if a struct or pointer to struct implements an interface Go工厂方法返回类型接口,而不是实现该接口的结构 - Go factory method returns type interface, not the struct which implements the interface 如何调用作为接口传递的 object 的嵌入式结构方法? - How to call an embedded struct method of an object passed as interface? 切片struct!=它实现的接口切片? - slice of struct != slice of interface it implements? 检查结构是否实现了给定的接口 - Check if struct implements a given interface 在 Go 中,如何检查接口是否实现了结构的所有导出方法? - In Go, how to check that an interface implements all of a struct's exported methods? 调用Go函数接受带有一层struct B的接口A的切片(B实现A) - Call Go function that accepts a slice of interface A with a slice of struct B (B implements A) go / types查找struct是否实现接口 - go/types finding if struct implements interface 当需要指针接收器时,如何正确检查结构字段是否实现了接口? - How do I properly check whether a struct field implements an interface when it requires a pointer receiver? 为什么返回一个实现了error接口的类型会自动调用Error()方法? - Why does returning a type that implements error interface call the Error() method automatically?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM