猿问

如何检查对象的动态结构中是否存在属性

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


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


手掌心
浏览 65回答 2
2回答

倚天杖

Go 不支持继承,但也许您会发现以下方法是可以容忍的。使用 来定义 的行为:interfaceAnimaltype 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

明月笑刀无情

姆科普里瓦是对的。Go不支持继承,也可以使用反射和接口{}ps:反映比接口更多的时间package mainimport (    "fmt"    "reflect")type Animal struct {    Name string    Origin string}type Bird struct {    Animal    Speed float32    CanFly bool}type Bear struct {    Animal    Lazy bool}func checkAminalSpeed (a interface{}){    v := reflect.ValueOf(a)    if f, ok := v.Type().FieldByName("Speed"); ok{        fmt.Printf("%v\n", f)    }}func main() {    checkAminalSpeed(Bird{})    checkAminalSpeed(Bear{})}
随时随地看视频慕课网APP

相关分类

Go
我要回答