arrays - 具有相同匿名字段但类型不同的 Go 结构数组

标签 arrays data-structures struct go

如果你想象我有以下声明:

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

Playground

我正在尝试拥有一系列车辆。然而,这是不可能的,因为它们都有不同的类型(即 CarBusBike 等...)

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])
}

Playground

您将如何实现这样的目标。还是我试图从错误的角度解决这个问题。我是 Go 新手。

最佳答案

Vehicle 嵌入在 CarBus 中,所以你的方向错了......它不像 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/

相关文章:

unit-testing - 如何对结构构造函数进行单元测试

c - 预期为 'double **' 但参数的类型为 'double (*)[2]'

c# - Jagged array 和 flatten array,哪个性能更好?

javascript - OO Javascript Game,如何将玩家添加到游戏的玩家数组中?

java - Android:使用什么数据结构来保存应用程序的数据

c - 使用新方法删除二叉树

c++ - 类方法中 For Loop 的运行时错误 - 数据结构

c++ - 在 C++ 中扩展数组

c - 在 C 中,将指向结构的指针值发送到函数时返回 float 会更改结构的值

c++ - 在 C++ 中对结构数组进行排序