go - 如何检查对象的动态结构中是否存在属性
问题描述
我对如何检查对象的动态结构中是否存在属性感到困惑。即,如果我们有以下结构:
type Animal struct {
Name string
Origin string
}
type Bird struct {
Animal
Speed float32
CanFly bool
}
type Bear struct {
Animal
Lazy bool
}
现在我有一个Animal
用作参数的函数:
func checkAminalSpeed (a Animal){
// if the struct of current animal doesn't have the Speed attribute
// print ("I don't have a speed")
//otherwise, return the speed of this animal
}
此函数试图检查变量的运行时类型以选择操作。
我想知道在这种情况下,如何编写这个checkAminalSpeed
函数?谢谢!
解决方案
Go 不支持继承,但也许你会发现下面的方法是可以接受的。
使用 aninterface
来定义Animal
的行为:
type Animal interface {
GetName() string
GetOrigin() string
GetSpeed() float32
}
使用将包含公共字段并实现行为的“基本”类型:
type AnimalBase struct {
Name string
Origin string
}
func (a AnimalBase) GetName() string { return a.Name }
func (a AnimalBase) GetOrigin() string { return a.Origin }
func (a AnimalBase) GetSpeed() float32 { return -1 }
嵌入“基本”类型并覆盖您需要的任何行为:
type Bird struct {
AnimalBase
Speed float32
CanFly bool
}
func (b Bird) GetSpeed() float32 { return b.Speed }
进而...
func checkAminalSpeed(a Animal) {
if speed := a.GetSpeed(); speed == -1 {
fmt.Println("I don't have speed")
} else {
fmt.Println(speed)
}
}
推荐阅读
- kubernetes - 从 ingress 迁移到 istio 时找不到 404
- python - 如何使用 M1chip 在我的 Mac 上运行 pyqt5
- boost - 为 websocket 提升堆栈协程,如何发布函数并从另一个线程恢复
- powerbi - 我可以在 Power BI 的组合图中将线放在两个轴上吗?(除了列)
- c - 这里的“x”是什么意思?
- javascript - Woocommerce结帐事件上的Javascript执行功能
- python - 如何使用 https 而不是 http 启动 Dockerized Python Flask 应用程序?
- python - tkinter 中的慢动画
- java - 获取资源器中文件的路径,即使它在 jar 中
- or-tools - IntVar 的域会影响 CP-SAT 求解器的性能吗