我有一个名为CarMotorbike的 struct ,它们是与其他 struct 的组合.例如:

type HasSeats struct {
  ...
}

type HasDoors struct {
   ...
}

type Car {
   HasSeats
   HasDoors
}

type Motorbike {
   HasSeats
}

我现在有一个CarMotorbike的实例.找出实例是否属于具有HasSeatsHasDoors的类型的最简单方法是什么?我找到了一种通过reflect模块的方法,但那是完全嘈杂的代码.如有任何帮助,我们将非常感激.

func CheckIfObjectHasDoors(carOrBike interface{}) bool {
    // ... ??
}

推荐答案

声明每个嵌入类型的唯一接口:

type Seats interface{ Seats() *HasSeats }
type Doors interface{ Doors() *HasDoors }

在每个类型上实现接口:

func (x *HasSeats) Seats() *HasSeats { return x }
func (x *HasDoors) Doors() *HasDoors { return x }

使用type assertions可确定合成类型是否包含以下嵌入类型之一:

var mb interface{} = &Motorbike{}
if _, ok := mb.(Seats); ok {
    fmt.Println("mb has seats")
}
if _, ok := mb.(Doors); !ok {
    fmt.Println("mb does not have doors")
}

https://go.dev/play/p/UeXgQoYu5tr

接口方法被声明为接收方,因为应用程序似乎希望直接访问该值.示例:

type HasSeats struct {
    Color string
}

...

var mb interface{} = &Motorbike{HasSeats: HasSeats{Color: "red"}}
if s, ok := mb.(Seats); ok {
    fmt.Println("mb has seats and the seat color is", s.Seats().Color)
}

https://go.dev/play/p/DsCpoW4HsUI

如果这不是您想要的,请删除返回值.

Go相关问答推荐

../golang/pkg/mod/github.com/wmentor/lemmas@v0.0.6/processor.go:72:9:未定义:令牌.进程

Go SQLCMD比Windows本机版本慢吗?

Golang内置打印(Ln)函数&S行为怪异

如何解析Go-Gin多部分请求中的 struct 切片

我怎样才能改进这个嵌套逻辑以使其正常工作并提高性能

如何将 goose 迁移与 pgx 一起使用?

生成一个 CSV/Excel,在 Golang 中该列的下拉选项中指定值

转到 bufio.Writer、gzip.Writer 并上传到内存中的 AWS S3

从 ApiGateway 中的 lambda Go 返回 Json

加载 docker 镜像失败

Yocto 无法交叉编译 GoLang Wails 应用程序

assert: mock: I don't know what to return because the method call was unexpected 在 Go 中编写单元测试时出错

对所有标志进行 ORing 的简短方法

NaN 是 golang 中的可比类型吗?

如何在Go中替换符号并使下一个字母大写

使用 oklog/run 来自 Go 编译器的错误(无值)用作值

Go 赋值涉及到自定义类型的指针

如何在 Prometheus 中正确检测区域和环境信息?

在 Go 中表达函数的更好方法( struct 方法)

为什么在 unsafe.Sizeof() 中取消引用 nil 指针不会导致panic ?