第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

訪問結(jié)構(gòu)屬性的空接口以避免代碼重復(fù)

訪問結(jié)構(gòu)屬性的空接口以避免代碼重復(fù)

Go
湖上湖 2022-06-21 16:25:56
我有 2 個(gè)不同的 API 版本,我正在嘗試重構(gòu)代碼以避免重復(fù)。在我的方法中,我可以接收來自 V1 或 V2 的對(duì)象(它們具有相同的屬性)。我想訪問這些屬性,目前我收到以下錯(cuò)誤:i.name undefined (type interface {} is interface with no methods)package mainimport "fmt"type V1 struct {  name string  age int  address string}type V2 struct {  name string  age int  }func main() {    v1 := &V1{name: "Susan", age: 15}    describe(v1)        v2 := &V2{name: "John", age: 21}    describe(v2)    }func describe(i interface{}) error {    fmt.Printf("(%v, %T)\n", i, i)    switch v := i.(type) {    default:               return fmt.Errorf("Error detected, unexpected type %T", v)           case *V1:        fmt.Println("*V1")        i = i.(*V1)         case *V2:        fmt.Println("*V2")        i = i.(*V2)    }    fmt.Println(i.name)    return nil}有什么建議么?
查看完整描述

2 回答

?
一只斗牛犬

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超2個(gè)贊

嘗試這個(gè):


   switch v := i.(type) {

    default:    

           return fmt.Errorf("Error detected, unexpected type %T", v)       

    case *V1:

        fmt.Println("*V1")

        fmt.Println(v.name)

    case *V2:

        fmt.Println("*V2")

        // v is of type *V2 here

    }

v已經(jīng)是您需要的類型。當(dāng)您重新分配時(shí)i,您又回到了interface{}.


查看完整回答
反對(duì) 回復(fù) 2022-06-21
?
翻過高山走不出你

TA貢獻(xiàn)1875條經(jīng)驗(yàn) 獲得超3個(gè)贊

i變量是interface{}類型,你應(yīng)該使用v它,它已經(jīng)是正確的*V1類型:v.name

參考:


查看完整回答
反對(duì) 回復(fù) 2022-06-21
  • 2 回答
  • 0 關(guān)注
  • 122 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)