1 回答

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上试试这个。
- 1 回答
- 0 关注
- 96 浏览
添加回答
举报