亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何檢查對象的動態結構中是否存在屬性

如何檢查對象的動態結構中是否存在屬性

Go
手掌心 2022-09-19 21:12:06
我對如何檢查對象的動態結構中是否存在屬性感到困惑。即,如果我們有以下結構:type Animal struct {    Name string    Origin string}type Bird struct {    Animal    Speed float32    CanFly bool}type Bear struct {    Animal    Lazy bool}現在我有一個函數用作參數:Animalfunc 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
查看完整描述

2 回答

?
倚天杖

TA貢獻1828條經驗 獲得超3個贊

Go 不支持繼承,但也許您會發現以下方法是可以容忍的。

使用 來定義 的行為:interfaceAnimal

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


查看完整回答
反對 回復 2022-09-19
?
明月笑刀無情

TA貢獻1828條經驗 獲得超4個贊

姆科普里瓦是對的。Go不支持繼承,也可以使用反射和接口{}


ps:反映比接口更多的時間


package main

import (

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

}


查看完整回答
反對 回復 2022-09-19
  • 2 回答
  • 0 關注
  • 91 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號