访问结构属性的空接口以避免代码重复

我有 2 个不同的 API 版本,我正在尝试重构代码以避免重复。在我的方法中,我可以接收来自 V1 或 V2 的对象(它们具有相同的属性)。我想访问这些属性,目前我收到以下错误:


i.name undefined (type interface {} is interface with no methods)

package main


import "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

}

有什么建议么?


湖上湖
浏览 140回答 2
2回答

一只斗牛犬

尝试这个:   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已经是您需要的类型。当您重新分配时i,您又回到了interface{}.

翻过高山走不出你

i变量是interface{}类型,你应该使用v它,它已经是正确的*V1类型:v.name参考:https://golang.org/ref/spec#Type_switches
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go