Go 空接口以访问结构属性以避免代码重复
我有两个不同的API版本,我试图重构代码以避免重复。 在我的方法中,我可以从V1或V2(具有相同属性)接收对象。 我想访问这些属性,目前我遇到以下错误:Go 空接口以访问结构属性以避免代码重复,go,Go,我有两个不同的API版本,我试图重构代码以避免重复。 在我的方法中,我可以从V1或V2(具有相同属性)接收对象。 我想访问这些属性,目前我遇到以下错误: i.name undefined (type interface {} is interface with no methods) 有什么建议吗?i变量属于接口{}类型,您应该使用v,它已经是正确的*V1类型:v.name 参考资料: 试试这个: switch v := i.(type) { default:
i.name undefined (type interface {} is interface with no methods)
有什么建议吗?
i
变量属于接口{}
类型,您应该使用v
,它已经是正确的*V1
类型:v.name
参考资料:
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
时,您将返回到界面{}
谢谢,我如何在交换机外访问v?我需要声明的变量类型可能是什么?v
在匹配的情况下是正确的变量类型。在开关外无法访问它。@gogasca为什么?在交换机外部,您有i
我无法访问i.name,如此处所示:fmt.Println(i.name)(刚刚编辑的原始问题)@gogasca,视情况而定。总的来说,是的。对于这个问题-不。
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
}