为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
湖上湖 2022-06-21 16:25:56
我有 2 个不同的 API 版本,我正在尝试重构代码以避免重复。在我的方法中,我可以接收来自 V1 或 V2 的对象(它们具有相同的属性)。我想访问这些属性,目前我收到以下错误: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贡献1784条经验 获得超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{}.


查看完整回答
反对 回复 2022-06-21
?
翻过高山走不出你

TA贡献1875条经验 获得超3个赞

i变量是interface{}类型,你应该使用v它,它已经是正确的*V1类型:v.name

参考:


查看完整回答
反对 回复 2022-06-21
  • 2 回答
  • 0 关注
  • 139 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号