如果你想象我有以下声明:
type Car struct {
Vehicle
engineType string
}
type Bus struct {
Vehicle
public bool
engineType string
}
type Bike struct {
Vehicle
motorbike bool
}
type Vehicle struct {
NumberWheels int
NumberPassengers int
Owner string
}
type Vehicles []Vehicle
我正在尝试拥有一系列车辆。然而,这是不可能的,因为它们都有不同的类型(即 Car
、Bus
、Bike
等...)
var myCar = Car{Vehicle{4, 4, "Me"}, "Manual"}
var myBike = Bike{Vehicle{2, 0, "Bob and I"}, false}
var myVehicles = Vehicles{myCar, myBike}
for i := range myVehicles {
fmt.Println(myVehicles[i])
}
您将如何实现这样的目标。还是我试图从错误的角度解决这个问题。我是 Go 新手。
最佳答案
Vehicle
嵌入在 Car
和 Bus
中,所以你的方向错了......它不像 Vehicle
是一个父类,因此您无法从此设计中获得您正在寻找的多态行为。您需要的是一个界面。
为了向您展示一个工作示例,我将使用空接口(interface)(它将允许您在集合中存储任何类型)。对于您的实际程序,您可能想要制作类似 IVehicle
接口(interface)的东西,并在其上放置所有车辆将拥有的任何通用方法,例如 Start()
或其他任何东西。 ..
https://play.golang.org/p/iPJbFYlo7o
稍微扩展一下嵌入的东西……这不是继承。您可以用它完成同样的事情,但是“汽车是车辆”的说法是不正确的。这实际上更像是组合,“Car has a Vehicle”。只是 Vehicle
的字段和方法被“提升”到 Car
,这意味着它们可以从 Car
的实例访问而无需另一个间接层,如 Car.Vehicle.FieldOnVehicle
。那不是你真正想要的。如果您想说“Car is a Vehicle”并且它是真的,那么 Vehicle
需要是 Car
实现的接口(interface)。
关于arrays - 具有相同匿名字段但类型不同的 Go 结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33835925/