小编Den*_*s M的帖子

Go 中的嵌入与继承

我正在尝试学习 Go,但我一直在努力反对它的一些概念,这些概念与其他语言相比有不同的应用。

假设我有一个结构

type Vehicle struct {
    Seats int
}
Run Code Online (Sandbox Code Playgroud)

我现在想要另一个结构,其中嵌入Vehicle

type Car struct {
    Vehicle
    Color string
}
Run Code Online (Sandbox Code Playgroud)

据我了解,该Car结构现在嵌入了 Vehicle.

现在我想要一个可以容纳任何车辆的功能

func getSeats(v Vehicle){
    return v.Seats
}
Run Code Online (Sandbox Code Playgroud)

但每当我尝试通过Car

    getSeats(myCar)
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:
cannot use myCar (value of type Car) as Vehicle value in argument to getSeats
但我的 IDE 告诉我myCar有一个Seats属性!

由此我了解到嵌入与继承不同。

我的问题是;是否有类似于 c++ 的结构继承,其中函数可以采用基本结构,或者这是 Go 处理完全不同的东西?我如何在“Go way”中实现这样的事情?

go

4
推荐指数
1
解决办法
3010
查看次数

标签 统计

go ×1