我有 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{}.

翻過高山走不出你
TA貢獻(xiàn)1875條經(jīng)驗(yàn) 獲得超3個(gè)贊
i
變量是interface{}
類型,你應(yīng)該使用v
它,它已經(jīng)是正確的*V1
類型:v.name
參考:
- 2 回答
- 0 關(guān)注
- 122 瀏覽
添加回答
舉報(bào)
0/150
提交
取消