首页 > 解决方案 > 如何检查对象的动态结构中是否存在属性

问题描述

我对如何检查对象的动态结构中是否存在属性感到困惑。即,如果我们有以下结构:

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

解决方案


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

https://play.golang.org/p/KIjfC7Rdyls


推荐阅读